bstack
bstack

Reputation: 2528

Decorating all methods of a class

Say I have a class Caller that calls another class's methods (i.e. Abc) in ruby:

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

Any time a method in class Abc is called, I need to decorate the call with a prefix that shows the Calling method class name and method name E.g. in the example above, I need the following output:

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

What is the best way to do this in ruby?

Upvotes: 3

Views: 791

Answers (1)

samuil
samuil

Reputation: 5081

You can create decorator that will not define any particular method, but will implement method_missing hook, and wrap every call in whatever code you need:

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

This way your decorator is unobtrusive. Moreover you can control which method calls are wrapped (e.g. by defining whitelist or blacklist in method_missing). This is quite clear way of defining aspects of behavior in well separated blocks of code.

Upvotes: 5

Related Questions