Ruby方法拦截 [英] Ruby method interception

查看:121
本文介绍了Ruby方法拦截的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拦截在ruby类上的方法调用,并且能够在方法的实际执行之前和之后做一些事情.我尝试了以下代码,但收到错误消息:

I want to intercept method calls on a ruby-class and being able to do something before and after the actual execution of the method. I tried the following code, but get the error:

MethodInterception.rb:16:in before_filter': (eval):2:in alias_method':未定义的方法 say_hello' for class家庭作业" (NameError) 来自(eval):2:in`before_filter'

MethodInterception.rb:16:in before_filter': (eval):2:inalias_method': undefined method say_hello' for classHomeWork' (NameError) from (eval):2:in `before_filter'

有人可以帮我做对吗?

class MethodInterception

  def self.before_filter(method)
    puts "before filter called"
    method = method.to_s
    eval_string = "
      alias_method :old_#{method}, :#{method}

      def #{method}(*args)
        puts 'going to call former method'
        old_#{method}(*args)
        puts 'former method called'
      end
    "
    puts "going to call #{eval_string}"
    eval(eval_string)
    puts "return"
  end
end

class HomeWork < MethodInterception
  before_filter(:say_hello)

  def say_hello
    puts "say hello"
  end

end

推荐答案

较少的代码已从原始更改.我只修改了2行.

Less code was changed from original. I modified only 2 line.

class MethodInterception

  def self.before_filter(method)
    puts "before filter called"
    method = method.to_s
    eval_string = "
      alias_method :old_#{method}, :#{method}

      def #{method}(*args)
        puts 'going to call former method'
        old_#{method}(*args)
        puts 'former method called'
      end
    "
    puts "going to call #{eval_string}"
    class_eval(eval_string) # <= modified
    puts "return"
  end
end

class HomeWork < MethodInterception

  def say_hello
    puts "say hello"
  end

  before_filter(:say_hello) # <= change the called order
end

这很好.

HomeWork.new.say_hello
#=> going to call former method
#=> say hello
#=> former method called

这篇关于Ruby方法拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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