I have a Config module in Ruby that I want to be able to add arbitrary variables to. I have created it using method_missing and instance_variable_set as follows:
module Conf
#add arbitrary methods to config array
def self.method_missing(m, *args)
args = args.pop if args.length==1
instance_variable_set("@#{m}", args)
end
end
However, I'm having trouble with dynamically creating accessors. When I try to use attr_accessor as follows:
module Conf
#add arbitrary methods to config array
def self.method_missing(m, *args)
args = args.pop if args.length==1
instance_variable_set("@#{m}", args)
module_eval("attr_accessor :#{m}")
end
end
I get the following:
Conf::s3_key('1234ABC') #Conf::s3_key=nil
And if I try to create the accessors separately:
module Conf
#add arbitrary methods to config array
def self.method_missing(m, *args)
args = args.pop if args.length==1
instance_variable_set("@#{m}", args)
module_eval("def self.#{m};@#{m};end")
module_eval("def self.#{m}=(val);@#{m}=val;end")
end
end
The following happens:
Conf::s3_key('1234ABC') # Conf::s3_key='1234ABC' - correct
but if I try to overwrite the value I get an error
Conf::s3_key('1234ABC') # ok
Conf::s3_key('4567DEF') #(eval):1:in `s3_key': wrong number of arguments (1 for 0) (ArgumentError)
What am I doing wrong?
missing_method's arguments. Is that correct?