我有一个班级,但如果某个字段属于特定值,我想要一些自定义行为。否则我想要默认行为。
class Foo
include Mongoid::Document
belongs_to :parent, :foreign_key => "parent_id", :class_name => "Pad"
has_many :children, :foreign_key => "parent_id", :class_name => "Pad"
field :bar, :type => String
def children
if self.bar == "some value"
# Do something special
else
return self.children # <- What goes here that isn't an infinite loop?
end
end
end
else分支应该是什么?
我不想重新实现孩子,所以我不只是寻找Foo.where(:parent_id =&gt; self.id)
答案 0 :(得分:1)
Active Support提供了一种方法来保持原始方法适用于这样的情况 - 它被称为“alias_method_chain”......它有点黑魔法,但你定义{method}_with_{condition}
并用{调用原始方法{ {1}}
在您的情况下:{method}_without_{condition}
,您可以通过致电children_with_bar
children_without_bar