3

假设我有一个类在 rubyCaller​​ 中调用另一个类的方法(即):Abc

class Caller
    def run
        abc = Abc.new
        abc.method1
        abc.method2
    end
end

class Abc
   def method1
      puts 'Method1 etc'
   end
   def method2
      puts 'Method2 etc'
   end
end

caller = Caller.new
caller.run

每次Abc调用类中的方法时,我都需要使用显示Calling方法类名称和方法名称的前缀来装饰调用例如在上面的示例中,我需要以下输出:

Caller.run - Method1 etc
Caller.run - Method2 etc

在红宝石中执行此操作的最佳方法是什么?

4

1 回答 1

5

您可以创建不会定义任何特定方法但将实现method_missing挂钩的装饰器,并将每个调用包装在您需要的任何代码中:

class Caller
  def initialize(object)
    @object = object
  end

  def method_missing(meth, *args, &block)
    puts 'wrapper'
    @object.public_send(meth, *args, &block)
  end
end

class YourClass
  def method1
    puts "method 1"
  end
end

c = Caller.new(YourClass.new)

c.method1

这样你的装饰器就不显眼了。此外,您可以控制包装哪些方法调用(例如,通过在 中定义白名单或黑名单method_missing)。这是在分离良好的代码块中定义行为方面的非常清晰的方法。

于 2013-06-17T09:15:24.160 回答