Dry way to call a method in each rail model

On the same lines as this question , I want to call acts_as_reportable

inside each model so that I can do one-off manual reports in the console in my dev environment (with a production data dump).

What's the best way to do this? The placement acts_as_reportable if ENV['RAILS_ENV'] == "development"

in each model becomes tiresome and not dry at all. Everyone says the monkey fix is ​​the devil, but the mixin seems like overkill.

Thanks!

+2


a source to share


3 answers


How do I create a Reportable class and get all models from it?



class Reportable
  acts_as_reportable if ENV['RAILS_ENV'] == "development"
end

class MyModel < Reportable
end

      

+1


a source


For me, the best way would be to add it to ActiveRecord :: Base in the initializer. I believe act_as_reportable is under the hood mixing. By doing this, when you can call the entire method that came with act_as_reportable, in all your models, only in the development environment.

I'll do it in a directory config/initializers

in a file named model_mixin.rb

or whatever.



class ActiveRecord::Base
  acts_as_reportable if (ENV['RAILS_ENV'] == "development")
end

      

The argument for using the monkey patch is dirty is up to you and how readable code, in my opinion, uses what you are comfortable with. This feature should be used and is always user dependent.

+3


a source


I use a mixin for common methods in all of 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 treated this somehow differently, but for me this seems to be the most legitimate way to DRY your models. A model equivalent to ApplicationController would be a neat solution, although I'm not sure how you do it or there is a decent argument against using it.

+1


a source







All Articles