attributes - Ruby: How to create attr_accessor on the fly -
i want know how create attr_accessor on fly. possible like:
attr_accessor "@#{key}" inside initialize method?
module mymodule def initialize(parameters = {}) parameters.each |key, value| instance_variable_set("@#{key}", value) unless value.nil? end end end class myclass include mymodule end clazz = myclass.new attr1: "arg1", attr2: "arg2", attr3: "arg3" # => #<myclass:0x43f6050 @attr1="arg1", @attr2="arg2", @attr3="arg3"> clazz.attr1 # !> nomethoderror: undefined method `attr1' #<myclass:0x43f6050 @attr1="arg1", @attr2="arg2", @attr3="arg3"> clazz.attr1="attr1" # !> nomethoderror: undefined method `attr1=' #<myclass:0x43f6050 @attr1="arg1", @attr2="arg2", @attr3="arg3">
you can define per instance accessors calling attr_accessor on instance's singleton class.
class structy def initialize(parameters = {}) parameters.each |key, value| singleton_class.send :attr_accessor, key instance_variable_set "@#{key}", value end end end
Comments
Post a Comment