如何在维护searchlogic功能的同时覆盖/添加method_missing?

时间:2012-03-21 14:07:56

标签: ruby-on-rails ruby

我想在抛出method_missing时向我的模型添加一些行为,但我知道searchlogic已经将它用于指定的搜索范围。

扩展method_missing功能的正确方法是什么?有没有办法对method_missing触发器做出反应?就像人们如何将函数绑定到javascript中的事件一样?

1 个答案:

答案 0 :(得分:9)

当你说你希望在丢失方法时发生某些事情时,你的意思是每次或只是当搜索逻辑没有找到某些东西时?前者非常简单:

def method_missing(name, *)
  if name =~ /foo/i
    # call your custom method
    # or for example define_method
  else
    # you do not want to handle the
    # method, so fall back to standard behavior
    super
  end
end

使用检查是否要处理丢失方法的条件替换name =~ /foo/i的位置。后者并不那么容易。我无法回答,因为我不知道搜索逻辑,但在调用自定义方法之前,你必须检查搜索逻辑是否找到了什么。