jmoreira jmoreira - 7 months ago 13
Ruby Question

List of decorated methods when using drapper decorators

I need way to get an array of names of all decorated methods created in a drapper decorator instance.

If i have two classes like:

class A
def foo
end
end

class ADecorator < Drapper::Decorator
def bar
end

def hi
end
end


Then i want to do something like:

decorated = ADecorator.decorate(A.new)
decorated.decorated_methods # => [:bar, :hi]


Closest to this is ruby's builtin
instance_methods
method but it returns both base object methods and decorator methods (In this example returns
[:foo, :bar, :hi]
)

Answer

You could monkey patch it in to Draper, e.g:

Put this in config/initializers/draper.rb:

 module DraperExtensions
   def decorated_methods
     instance_methods.to_set - Draper::Decorator.instance_methods.to_set   
   end
 end

 Draper::Decorator.extend DraperExtensions

Then you will be able to call:

ADecorator.decorated_methods
Comments