DRY way of calling a method in every rails model
Along the same lines as this question, I want to call acts_as_reportable
inside every model so I can do one-off manual reports in the console in my dev environment (with a dump of the production data).
What's the best way to do this? Putting acts_as_reportable if ENV['RAILS_ENV'] == "development"
in every model is getting tedious and isn't very DRY at all. Everyone says monkey patching is the devil, but a mixin seems overkill.
开发者_开发百科Thanks!
For me the best way will be to add it into the ActiveRecord::Base in the initializer. I believe the acts_as_reportable is a mixin under the hood. By doing this, when you will be able to call all the method that came with acts_as_reportable in all your models in development environment only.
I will do it in the config/initializers
directory, in a file called model_mixin.rb
or anything that you wish.
class ActiveRecord::Base
acts_as_reportable if (ENV['RAILS_ENV'] == "development")
end
The argument of using monkey patch is dirty depends on yourself and how readable the code is, in my opinion, use what you are comfortable with. The feature are there to be used and it always depends on the user.
What about creating a Reportable class and deriving all the models from it?
class Reportable
acts_as_reportable if ENV['RAILS_ENV'] == "development"
end
class MyModel < Reportable
end
I use a mixin for common methods across all my models:
module ModelMixins
# Splits a comma separated list of categories and associates them
def process_new_categories(new_categories)
unless new_categories.nil?
for title in new_categories.split(",")
self.categories << Category.find_or_create_by_title(title.strip.capitalize)
end
self.update_counter_caches
end
end
end
I considered doing it in other ways, but to me this seems to be the most legitimate way of DRYing up your models. A model equivalent of the ApplicationController would be a neat solution, though I'm not sure how you'd go about that, or whether there's a decent argument against having one.
精彩评论