我需要一种方法来创建关联集合方法(特别是附加<<)私有。这是一个例子:
class Foo < ActiveRecord::Base
has_many :bars
def add_bar (bar)
# does something extra first
# but still also use the <<, ultimately
bars.send(:<<, bar)
end
end
基本上,我不希望应用程序的任何部分使用&lt;&lt;就其本身而言,我需要它来完成“add_bar”方法。有什么建议?
非常感谢!
答案 0 :(得分:2)
有private_class_method(我不知道自己:))。您可以尝试一些
的内容class Foo < ActiveRecord::Base
has_many :bars do
private_class_method :<<
end
def add_bar (bar)
# does something extra first
# but still also use the <<, ultimately
bars.send(:<<, bar)
end
end
没有测试,看它是否有效。
答案 1 :(得分:1)
创建位于关联前面的代理类,并将原始关联设为私有。这是一个例子:
class Foo < ActiveRecord::Base
has_many :_bars, :class_name => "Bar"
private :_weeks
class BarsProxy
include ::Enumerable
def initialize(weeks)
@weeks = weeks
end
def each
yield @weeks.each
end
def create(args = {})
@weeks.create(args)
end
# Plus whatever other methods you want to use on the collection.
end
def weeks
@weeks ||= WeeksProxy.new(_weeks)
end
end