I have this model:
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
I have a feeling that this can be done shorter and more elegant. Does anyone have an idea?
- Jacob
BTW. Can anyone tell me what the asterisk in front of CUSTOM_FIELDS does? I know what it does in a method definition (def foo(*args)) but not here…
Alright first off: never
10000000000.times { puts "ever" }useevalwhen you don’t know what you’re doing. It is the nuclear bomb of the Ruby world in the way that it can wreak devestation across a wide area, causing similar symptoms to radiation poisoning throughout your code. Just don’t.With that in mind:
Now for some notes:
*CUSTOM_FIELDSpassed intoattr_accessoruses what is referred to as the “splat operator”. By calling it in this way, the elements of theCUSTOM_FIELDSarray will be passed as individual arguments to theattr_accessormethod rather than as one (the array itself)sendmethod to call methods we don’t know the names of during programming, rather than the evileval.Other than that, I cannot find anything else to refactor about this code.