I have a class but I want some customized behavior if a field is of a particular value. Otherwise I want the default behavior.
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
What should the else branch be?
I do not want to reimplement children so I’m looking for more than just Foo.where(:parent_id => self.id)
Active Support provides a method to keep the original method around for cases like this — it’s called “alias_method_chain”… It’s a bit of black magic, but you define the
{method}_with_{condition}and call the original with{method}_without_{condition}In your case:
children_with_barand you get to the original by callingchildren_without_bar