Hi i have a code i would like to refactor
def gear_type
@gear_type ||= self.class.gear_types.find{|gears| gears["id"]==source["gear_type_id"]}["text"] if source["gear_type_id"]
end
def brand
@brand ||= self.class.brands.find{|node| node["id"]==source["brand_id"].to_s}["text"] if source['brand_id']
end
what is best way? to use eval or define method? i’ve tried this but there are some error i can’t discover yet:
%w(gear_type brand).each do |meth|
define_method(meth){
instance_variable_get("@#{meth}") rescue
instance_variable_set("@#{meth}", self.class.send(meth.pluralize).find{|node| node["id"]==source["#{meth}_id"]}["text"]) if source["#{meth}_id"]
}
end
I’d just write a common finder method that you can parameterize: