嗨,我有一个代码,我想重构如何重构ruby代码?
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
什么是最好的办法吗?使用eval还是定义方法?我已经尝试过这一点,但也有一些错误,我不能发现尚未:
%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
代码审查/重构现在在http://codereview.stackexchange.com –