, . , Rails -. -, . ALL_CAPS_WORDS Ruby ++. Bleah.
, . ? , Rails, , ?
, DB, , , Lichtamberg:
def self.method_missing(category, *args)
@categories ||= {}
if (@categories[category] = find_by_name(category.to_s))
class_eval "def self.#{category.to_s}; @categories[#{category}]; end"
return @categories[category]
end
super
end
, , Category.ham, , find_by_name("ham"), , method_missing() . OpenStruct, BTW; , .
(Of course, you still risk that, since they are all stored in memory, your Rails application will not reflect any changes you make to your category objects. This suggests that the changes will not occur, is it really important to you to determine if this is really an assumption for your application, you can always put a callback after_updatein your code that resets @@categoriesif this is a problem, but at this point it starts to get complicated.)
source
share