0

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

If i have two classes like:

class A
  def foo
  end
end

class ADecorator < Draper::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])

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
jmoreira
  • 1,556
  • 2
  • 16
  • 26

1 Answers1

1

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
Community
  • 1
  • 1
davetapley
  • 17,000
  • 12
  • 60
  • 86
  • It kinda works, it returns the 'decorated methods' and also `method_missing` but this is not difficult to exclude. Is there a way to do something like this without using an initializer? Let's say create a regular instance method in the decorator or maybe put it in a mixin or a base class which is then inherited by the decorator? – jmoreira Apr 21 '16 at 00:59
  • end up making a method inside the class instead of monkey patching removing method missing from the list! – jmoreira Apr 21 '16 at 02:37
  • I suspect the `method_missing` occurs as a result of Draper's [`delegate`](https://github.com/drapergem/draper#delegating-methods) functionality. – davetapley Apr 21 '16 at 18:28
  • 1
    FYI there's more explanation of the monkey patching approach I used [here](http://stackoverflow.com/questions/4470108/when-monkey-patching-a-method-can-you-call-the-overridden-method-from-the-new-i/4471202#4471202). – davetapley Apr 21 '16 at 18:30
  • nice question out there in the link! – jmoreira Apr 22 '16 at 12:24