arrays - create instance variable dynamically in ruby unknown number variables needed -



arrays - create instance variable dynamically in ruby unknown number variables needed -

this problem "i trying create generic object, thought of "dynamic schema object" each schema object have different number of instances variables." , approach doesn't work.

class genericobjectarray def initialize @data_fields = [] end def data_fields(t) @data_fields << t end def initialize(attrs = {}) attrs.each { |attr,val| instance_variable_set "@#{attr}", val } end end p genericobjectarray.new(:data_fields=> "may_sales", :data_fields=>"june_sales", :data_fields=>"july_sales")

this approach, bu doesnt work. set may_sales, june_sales, july_sales instance variables. set 3 instance variables. returns lastly one. genericobjectarray:0x007f8c5b883cd8 @data_fields="july_sales"

think approach:

you have objects (lets genericobject) objects have many attributes (genericobject#attributes => [genericobject::attribute]) attributes have name, value, , type (genericobject::attribute#value, #name , #type)

which translates code this:

class genericobject attr_accessor :attributes def add_attribute(name, value, type) (@attributes ||= []) << attribute.new(name, value, type) end class attribute attr_accessor :name, :value, :type def initialize(name, value, type) @name, @value, @type = name, value, type end end end # so... cat = genericobject.new cat.add_attribute :leg_number, 4, :integer cat.add_attribute :fur_color, 'orange', :color cat.add_attribute :name, 'garfield', :string cat.attributes.each { |attr| puts "my cat's #{attr.name} #{attr.value} (#{attr.type})" } # cat's leg_number 4 (integer) # cat's fur_color orange (color) # cat's name garfield (string)

you can create fancy initializer genericobject or whatever see fit. or can little fix

class genericobjectarray def initialize(attrs = {}) attrs.each { |attr,val| instance_variable_set "@#{attr}", val } end end genericobjectarray.new(:data_fields=> ["may_sales", "june_sales", "july_sales"])

ruby arrays variables instance dynamically-generated

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -