在每个rails模型中调用方法的DRY方式

时间:2010-05-11 05:35:03

标签: ruby-on-rails

this question一样,我想在每个模型中调用acts_as_reportable,这样我就可以在我的开发环境中的控制台中进行一次性手动报告(转储生产数据) )。

最好的方法是什么?将acts_as_reportable if ENV['RAILS_ENV'] == "development"放在每个模型中变得乏味,并且根本不是很干。每个人都说猴子补丁是魔鬼,但混合物似乎有点过分。

谢谢!

3 个答案:

答案 0 :(得分:3)

对我来说,最好的方法是将它添加到初始化程序中的ActiveRecord :: Base中。我相信acts_as_reportable是一个混合体。通过这样做,当您只能在开发环境中的所有模型中调用acts_as_reportable附带的所有方法时。

我将在config/initializers目录,名为model_mixin.rb的文件或您希望的任何内容中执行此操作。

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

使用猴子补丁的论点很脏,取决于你自己以及代码的可读性,在我看来,使用你熟悉的东西。该功能可供使用,它始终取决于用户。

答案 1 :(得分:1)

如何创建一个Reportable类并从中派生出所有模型呢?

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

class MyModel < Reportable
end

答案 2 :(得分:1)

我在所有模型中使用mixin作为常用方法:

 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

我考虑过以其他方式做到这一点,但对我而言,这似乎是干燥模型的最合法方式。相当于ApplicationController的模型将是一个简洁的解决方案,虽然我不确定你会怎么做,或者是否有一个不错的论据反对拥有它。