Ruby on Rails:模型间共享方法

25

如果我的几个模型都有一个隐私列,那么是否有一种方法可以编写一个适用于所有模型的方法,我们称之为is_public?

因此,我希望能够执行object_var.is_public?

2个回答

52

一种可能的方法是将共享方法放在一个类似于这样的模块中(RAILS_ROOT/lib/shared_methods.rb

module SharedMethods
  def is_public?
    # your code
  end
end

那么您需要在每个需要使用这些方法的模型中包含此模块(即app/models/your_model.rb)。

class YourModel < ActiveRecord::Base
  include SharedMethods
end

更新:

在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

1
self.class 会返回在调用该方法的上下文中所属的类。例如,如果你执行 YourModel.new.is_public?,那么 self.class 将会是 YourModel。 - lambdabutz

7

您还可以通过从包含共享方法的公共祖先继承模型来实现此操作。

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

class ChildModel < BaseModel
end

实际上,jigfox的方法通常更好,因此不要仅仅出于对OOP理论的热爱而感到必须使用继承 :)


我想用这种方式实现,但是我无法让它工作... :( - Augustin Riedinger
对我不起作用,创建了一个共享类TestClientManager,现在它尝试为其创建一个表:Table 'socha-webapp.test_client_managers' doesn't exist - xeruf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接