Ruby 有什么方法可以在 method_missing 之前捕获消息吗?

发布于 2024-12-27 14:42:07 字数 229 浏览 3 评论 0原文

我知道 method_missing 是 Ruby 处理消息时的最后手段。我的理解是,它会沿着对象层次结构向上查找与符号匹配的声明方法,然后向下查找最低声明的 method_missing。这比标准方法调用慢得多。

是否可以拦截在此之前发送的消息?我尝试重写 send,这在显式调用 send 时有效,但在隐式调用时则无效。

I understand that method_missing is something of a last resort when Ruby is processing messages. My understanding is that it goes up the Object hierarchy looking for a declared method matching the symbol, then back down looking for the lowest declared method_missing. This is much slower than a standard method call.

Is it possible to intercept sent messages before this point? I tried overriding send, and this works when the call to send is explicit, but not when it is implicit.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-柠檬树下少年和吉他 2025-01-03 14:42:07

据我所知没有。

性能最佳的方法通常是使用 method_missing 动态地将方法添加到类的调用中,这样开销就只会产生一次。从那时起,它像任何其他方法一样调用该方法。

例如:

class Foo
  def method_missing(name, str)

    # log something out when we call method_missing so we know it only happens once
    puts "Defining method named: #{name}"

    # Define the new instance method
    self.class.class_eval <<-CODE
      def #{name}(arg1)
        puts 'you passed in: ' + arg1.to_s
      end
    CODE

    # Run the instance method we just created to return the value on this first run
    send name, str
  end
end

# See if it works
f = Foo.new
f.echo_string 'wtf'
f.echo_string 'hello'
f.echo_string 'yay!'

运行时会输出以下内容:

Defining method named: echo_string
you passed in: wtf
you passed in: hello
you passed in: yay!

Not that I know of.

The most performant bet is usually to use method_missing to dynamically add the method being to a called to the class so that the overhead is only ever incurred once. From then on it calls the method like any other method.

Such as:

class Foo
  def method_missing(name, str)

    # log something out when we call method_missing so we know it only happens once
    puts "Defining method named: #{name}"

    # Define the new instance method
    self.class.class_eval <<-CODE
      def #{name}(arg1)
        puts 'you passed in: ' + arg1.to_s
      end
    CODE

    # Run the instance method we just created to return the value on this first run
    send name, str
  end
end

# See if it works
f = Foo.new
f.echo_string 'wtf'
f.echo_string 'hello'
f.echo_string 'yay!'

Which spits out this when run:

Defining method named: echo_string
you passed in: wtf
you passed in: hello
you passed in: yay!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文