我有这样的模式:重构这个Ruby和Rails代码
class Event < Registration
serialize :fields, Hash
Activities=['Annonce', 'Butiksaktivitet', 'Salgskonkurrence']
CUSTOM_FIELDS=[:activity, :description, :date_from, :date_to, :budget_pieces, :budget_amount, :actual_pieces, :actual_amount]
attr_accessor *CUSTOM_FIELDS
before_save :gather_fields
after_find :distribute_fields
private
def gather_fields
self.fields={}
CUSTOM_FIELDS.each do |cf|
self.fields[cf]=eval("self.#{cf.to_s}")
end
end
def distribute_fields
unless self.fields.nil?
self.fields.each do |k,v|
eval("self.#{k.to_s}=v")
end
end
end
end
我有一种感觉,这是可以做到更短,更优雅。有人有想法吗?
- 雅各
BTW。任何人都可以告诉我CUSTOM_FIELDS前的星号是干什么的?我知道它的方法定义(DEF foo的(*参数)),但不是在这里......
我认为这个问题在适合更好的代码审查(http://codereview.stackexchange.com/ - 测试版现在处于活动状态!) – ecoologic 2011-01-20 23:10:00