2016-04-20 113 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