I created a mixin module called BaseProduct. This module has an
initialize method in it. I am trying to use some meta-programming to
set variables in initialize from the class that the module is in
included in… I pass a CSV row into the initialize method and it needs
to set all the variables. Its a bit confusing trying to explain it, but
here is what it looks like:
Note: the real world scenario is a bit more complicated using different
objects, but I simplified it here to use a “product” scenario.
#<table_fields_from_class> is pseudo-code
Module BaseProduct
def self.included(base)
#some stuff goes here
end
def initialize(attributes = nil,row)
super(attributes)
<table_fields_from_class>.each_with_index do |field,i|
#NOTE: row is an array of values (csv row to array)
eval(“self.#{field} = row[#{i}]”)
end
end
end
class ShirtProduct < ActiveRecord::Base
<table_fields_from_class> = [“size”,“color”,“collar_type”]
include BaseProduct
end
class PantsProduct < ActiveRecord::Base
<table_fields_from_class> = [“waist”,“length”,“material”]
include BaseProduct
end
I am import data from different CSVs (one for each type of product…
each having different attributes) into tables by so using this code I
want to be able to do this in rails:
pants = PantsProduct.new(nil,csv_row)
pants.save
I dont want to have to code an initialize method for every type of
product and I thought it would be much easier to use metaprogramming and
just pass an array of fields to a base initialize method. I may be way
off here and there may be a completely different design pattern that
would support this use case better, but this is what I originally came
up with. I have tried several things with attr_accessor, CONSTANTS,
etc… but I have not been able to get the initialize method to see
variables I set in the class. I am probably missing something simple as
I don’t fully understand the module’s scope of access to the class…
seems pretty straight forward vice-versa (class from module), but the
other way around is confusing me a bit. let me know if you got any
ideas. THANKS!