简体   繁体   English

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

[英]How do I override / add to the method_missing while maintaining searchlogic functionality?

I want to add some behavior to my model when method_missing is thrown, but I know searchlogic already uses that for their named search scopes. 我想在抛出method_missing时向我的模型添加一些行为,但我知道searchlogic已经将它用于它们的命名搜索范围。

What is the proper way to extend method_missing functionality? 扩展method_missing功能的正确方法是什么? Is there a way to react to a method_missing trigger? 有没有办法对method_missing触发器做出反应? Much like how one would bind functions to events in javascript? 就像如何将函数绑定到javascript中的事件一样?

when you say you want something to happen when method missing is thrown, do you mean every time or just when search logic didn't find something? 当你说你想要在丢失方法时发生某些事情时,你的意思是每次还是只是当搜索逻辑没有找到某些东西时? The former is quite simple: 前者非常简单:

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

Where you replace name =~ /foo/i with a condition that checks whether you want to handle the missing method or not. 使用检查是否要处理丢失方法的条件替换name =~ /foo/i The latter is not as easy. 后者并不那么容易。 I can't answer it, because i do not know search logic, but you'd have to check whether search logic found something or not before calling your custom method. 我无法回答它,因为我不知道搜索逻辑,但在调用自定义方法之前,您必须检查搜索逻辑是否找到了某些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM