Ruby on Rails:模型之间的共享方法

Nul*_*uli 21 ruby-on-rails

如果我的一些模型有一个隐私列,有没有办法可以编写所有模型共享的方法,我们称之为is_public?

所以,我希望能够做object_var.is_public?

jig*_*fox 45

一种可能的方法是将共享方法放在module这样的(RAILS_ROOT/lib/shared_methods.rb)中

module SharedMethods
  def is_public?
    # your code
  end
end
Run Code Online (Sandbox Code Playgroud)

然后你需要在每个应该有这些方法的模型中包含这个模块(即app/models/your_model.rb)

class YourModel < ActiveRecord::Base
  include SharedMethods
end
Run Code Online (Sandbox Code Playgroud)

更新:

在Rails 4中,有一种新方法可以做到这一点.你应该像这样放置共享代码app/models/concerns而不是lib

您也可以像这样添加类方法并在包含上执行代码

module SharedMethods
  extend ActiveSupport::Concern

  included do
    scope :public, -> { where(…) }
  end

  def is_public?
    # your code
  end

  module ClassMethods
    def find_all_public
      where #some condition
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


zet*_*tic 6

您也可以通过从包含共享方法的共同祖先继承模型来完成此操作.

class BaseModel < ActiveRecord::Base
  def is_public?
    # blah blah
   end
end

class ChildModel < BaseModel
end
Run Code Online (Sandbox Code Playgroud)

在实践中,jigfox的方法通常效果更好,所以不要仅仅出于对OOP理论的热爱而使用继承的义务:)