首页 > 解决方案 > 在多个方法中添加相同的代码

问题描述

我有一个有 N 个方法的类。

class MyClass
  def self.method_one(params)
    #specific code
  end

  def self.method_two(params)
    #specific code
  end
end

我需要为该类中创建的每个方法添加相同的代码。我需要将代码放在“开始和救援”之间

我尝试了以下方法,但没有成功:

class MyClass < BaseClass
  add_rescue :method_one, :method_two, Exception do |message|
    raise message                                                     
  end

  def self.method_one(params)
    #specific code
  end

  def self.method_two(params)
    #specific code
  end
end

我创建了一个方法来改变方法

class BaseClass
  def self.add_rescue(*meths, exception, &handler)
    meths.each do |meth|
      old = instance_method(meth)
      define_method(meth) do |*args|
        begin
          old.bind(self).call(*args)
        rescue exception => e
          handler.call(e)
        end
      end
    end
  end
end

我总是收到错误消息:未定义的方法 `method_one 'for Myclass: Class

标签: ruby-on-railsrubymetaprogramming

解决方案


MyClass#method_one是一个类方法,或者换句话说,是 的实例方法MyClass.singleton_class。也就是说,我们可以Module#prepend将所需的功能MyClass.singleton_class

def self.add_rescue(*meths, exception, &handler)
  mod =
    Module.new do
      meths.each do |meth|
        define_method meth do |*args, &λ|
          begin
            super(*args, &λ)
          rescue exception => e
            handler.(e) 
          end
        end
      end
    end

  MyClass.singleton_class.prepend(mod)
end

推荐阅读