rspec - Circular require issue with Ruby -
i trying implement currency based application using ruby, find that:
require 'dollar' require 'franc' puts 'why not work?' class money attr_reader :amount def self.dollar(number) dollar.new number end def ==(other) self.amount == other.amount end def self.franc(number) franc.new(number) end end
i have franc
class looks this:
require 'money' class franc < money attr_reader :amount def initialize(amount) @amount = number end def times(mul) amount = @amount * mul franc.new(amount) end def ==(other) return false unless other.is_a? self.class super end end
this direct translation of of code kent beck book ruby. when run bin/rspec
see:
/home/vamsi/do/wycash/lib/franc.rb:3:in `<top (required)>': uninitialized constant money (nameerror) /home/vamsi/do/wycash/lib/money.rb:2:in `require' /home/vamsi/do/wycash/lib/money.rb:2:in `<top (required)>' /home/vamsi/do/wycash/lib/dollar.rb:1:in `require' /home/vamsi/do/wycash/lib/dollar.rb:1:in `<top (required)>' /home/vamsi/do/wycash/spec/dollar_spec.rb:1:in `require' /home/vamsi/do/wycash/spec/dollar_spec.rb:1:in `<top (required)>' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `block in load_spec_files' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `each' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `load_spec_files' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:100:in `setup' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:86:in `run' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:71:in `run' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:45:in `invoke' /home/vamsi/do/wycash/.bundle/ruby/2.3.0/gems/rspec-core-3.5.4/exe/rspec:4:in `<top (required)>' bin/rspec:17:in `load' bin/rspec:17:in `<main>'
you should put require 'franc'
after defined money in first script.
the class money defined when ruby executes second_script.
edit: circular require isn't issue :
# a.rb puts "a" require_relative 'b' # b.rb puts "b" require_relative 'a' # ruby a.rb b
replacing require_relative load './b.rb'
result in infinite loop , "stack level deep" error.
still, should define money in money.rb, franc in franc.rb, ... , not put franc in money.
Comments
Post a Comment