2

I have a class that has N methods.

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

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

I need to add the same code for each method created in that class. I need to put the code between "begin and rescue"

I tried the following, but I did not succeed:

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

I created a method to change the methods

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

I always get the error message: undefined method `method_one 'for Myclass: Class

1
  • Sidenote: even if this worked, you discard the block that might be passed to the method in your wrapper. Commented Jun 15, 2018 at 12:58

1 Answer 1

3

MyClass#method_one is a class method or, in other words, the instance method of MyClass.singleton_class. That said, we can Module#prepend the desired functionality to 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.