2016-04-20 110 views
0

我需要一种方法来获取装饰器实例中创建的所有装饰方法的名称数组。使用draper装饰器时的装饰方法列表

如果我有两个类,如:

class A 
    def foo 
    end 
end 

class ADecorator < Draper::Decorator 
    def bar 
    end 

    def hi 
    end 
end 

然后我想要做的事,如:

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

最接近这是Ruby的内建instance_methods方法,但它同时返回基地对象的方法和装饰方法(在这个例子中返回[:foo, :bar, :hi]

回答

1

你可以monkey patch它在德雷珀,例如:

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 

然后你就可以拨打电话:

ADecorator.decorated_methods 
+0

它还挺有效,则返回“装饰方法”,也'method_missing'但这不是难以排除。有没有办法做这样的事情,而不使用初始化?比方说,在装饰器中创建一个常规的实例方法,或者将其放入一个混装或基类中,然后由装饰器继承它们? – jmoreira

+0

最终在类内部创建一个方法,而不是从列表中删除猴子修补删除方法! – jmoreira

+0

我怀疑'method_missing'是Draper的['delegate'](https://github.com/drapergem/draper#delegating-methods)功能的结果。 – dukedave