为 Ruby 模块中的每个方法调用执行代码 [英] Executing code for every method call in a Ruby module

查看:26
本文介绍了为 Ruby 模块中的每个方法调用执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Ruby 1.9.2 编写一个模块,它定义了几个方法.当调用这些方法中的任何一个时,我希望它们中的每一个都首先执行某个语句.

I'm writing a module in Ruby 1.9.2 that defines several methods. When any of these methods is called, I want each of them to execute a certain statement first.

module MyModule
  def go_forth
    a re-used statement
    # code particular to this method follows ...
  end

  def and_multiply
    a re-used statement
    # then something completely different ...
  end
end

但我想避免在每个方法中显式地放置重用语句代码.有什么办法吗?

But I want to avoid putting that a re-used statement code explicitly in every single method. Is there a way to do so?

(如果重要,重用语句将使每个方法在调用时打印自己的名称.它将通过puts __method__的一些变体来实现.)

(If it matters, a re-used statement will have each method, when called, print its own name. It will do so via some variant of puts __method__.)

推荐答案

像这样:

module M
  def self.before(*names)
    names.each do |name|
      m = instance_method(name)
      define_method(name) do |*args, &block|  
        yield
        m.bind(self).(*args, &block)
      end
    end
  end
end

module M
  def hello
    puts "yo"
  end

  def bye
    puts "bum"
  end

  before(*instance_methods) { puts "start" }
end

class C
  include M
end

C.new.bye #=> "start" "bum"
C.new.hello #=> "start" "yo"

这篇关于为 Ruby 模块中的每个方法调用执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆