2011-11-29 75 views
0

我有一个类,但我想要一些自定义的行为,如果一个字段是一个特定的值。否则,我想要默认行为。呼叫默认的mongoid函数

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 => self.id)

回答

1

活动提供支持,以保持原来的方法周围情况等的方法这一点 - 这就是所谓的“alias_method_chain” ......这是一个有点黑魔法,但你定义{method}_with_{condition}{method}_without_{condition}

调用原来你的情况:children_with_bar并通过调用children_without_bar

得到原来的
require 'active_support' 
require 'mongoid' 

class Foo 
    include Mongoid::Document 
    has_many :children, :foreign_key => "parent_id", :class_name => "Pad" 
    field :bar 

    def children_with_bar 
    if self.bar == "some value" 
     return "yooooo" 
    else 
     children_without_bar 
    end 
    end 

    alias_method_chain :children, :bar 
end 


Foo.new(:bar=>"some value").children 
=> "yooooo" 
Foo.new(:bar=>"different").children 
## Will run original children method