I have a homework problem to create a simple DSL configuration for Ruby.
The problem is in method_missing
. I need to print out values of keys, but they're printing out automaticaly, not by command.
init.rb:
require_relative "/home/marie/dsl/store_application.rb"
config = Configus.config do |app|
app.environment = :production
app.key1 = "value1"
app.key2 = "value2"
app.group1 do |group1|
group1.key3 = "value3"
group1.key4 = "value4"
end
end
store_application.rb:
class Configus
class << self
def config
yield(self)
end
# attr_accessor :environment,
# :key1,
# :key2,
# :key3,
# :key4
def method_missing(m, args)
puts args
end
def group1(&block)
@group1 ||= Group1.new(&block)
end
end
class Group1
class << self
def new
unless @instance
yield(self)
end
@instance ||= self
end
# attr_accessor :key1,
# :key2,
# :key3,
# :key4
def method_missing(m, *args)
p m, args
end
end
end
end
Ruby's init.rb output:
marie@marie:~/dsl$ ruby init.rb
production
value1
value2
:key3=
["value3"]
:key4=
["value4"]
The problem is that the values are printing automatically, I need to print them out using:
config.key1 => 'value1'
config.key2 => 'value2'
config::Group1.key3 => 'value3'
config::Group1.key4 => 'value4'