G
goodieboy
Hi,
I experimenting with this config class. I'm hoping to get something
really easy to write and I'm on to something here, well at least I
thought I was. This class allows me to build a nested Has like:
Config.new do
simple_setting 'the value'
nested {
nested_key 'nested_value'
deep_nesting {
deep_nested_key 'deep nested value'
}
}
end
The problem is that if I have a key that matches the name of the Hash
class method set, problems arise. Currently, the only way that the
settings can be made is if the method doesn't exist (using
method_missing). Obviously, this is a problem. Would someone mind
kicking in here and giving me a clue as to how I could solve this
problem? Is it possible to do what I want, with out having to use
method_missing?
Thanks - matt
class Config < Hash
def initialize(init_data=nil, &block)
update init_data if init_data.respond_to?
each_pair)
configure(&block)
end
def configure(&block)
instance_eval(&block) if block_given?
end
def method_missing(method, data=nil, &block)
self[method] = data
if data.nil?
# if data.nil?, create a skelton using the method as key (method
chaining)
return self[method] = self.class.new(data, &block)
end
self
end
end
I experimenting with this config class. I'm hoping to get something
really easy to write and I'm on to something here, well at least I
thought I was. This class allows me to build a nested Has like:
Config.new do
simple_setting 'the value'
nested {
nested_key 'nested_value'
deep_nesting {
deep_nested_key 'deep nested value'
}
}
end
The problem is that if I have a key that matches the name of the Hash
class method set, problems arise. Currently, the only way that the
settings can be made is if the method doesn't exist (using
method_missing). Obviously, this is a problem. Would someone mind
kicking in here and giving me a clue as to how I could solve this
problem? Is it possible to do what I want, with out having to use
method_missing?
Thanks - matt
class Config < Hash
def initialize(init_data=nil, &block)
update init_data if init_data.respond_to?
configure(&block)
end
def configure(&block)
instance_eval(&block) if block_given?
end
def method_missing(method, data=nil, &block)
self[method] = data
if data.nil?
# if data.nil?, create a skelton using the method as key (method
chaining)
return self[method] = self.class.new(data, &block)
end
self
end
end