如果我的一些模型有一个隐私列,有没有办法可以写出所有模型共享的一种方法,我们可以称之为is_public?Ruby on Rails:模型之间的共享方法
所以,我想能够做object_var.is_public?
如果我的一些模型有一个隐私列,有没有办法可以写出所有模型共享的一种方法,我们可以称之为is_public?Ruby on Rails:模型之间的共享方法
所以,我想能够做object_var.is_public?
一种可能的方式是把共享方法在module
像这样(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
UPDATE:
在Rails 4有一个new way要这样做。你应该把从一个共同的祖先继承模型的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
你也可以做到这一点共享这样的代码,其包括共享方法。
class BaseModel < ActiveRecord::Base
def is_public?
# blah blah
end
end
class ChildModel < BaseModel
end
在实践中,jigfox的做法通常能够直接越好,所以不要觉得有义务使用继承仅仅是出于爱的OOP理论:)
我想这样做。但我不能让它工作...... :( – 2014-09-25 20:21:14
但我需要通过一个变量告诉方法我正在使用什么类... – NullVoxPopuli 2010-08-11 19:14:56
self.class会给你所调用的方法上下文中的任何类。所以,举个例子,如果你做了YourModel.new.is_public?,self.class就是YourModel。 – lambdabutz 2010-08-11 19:17:36