Rails 3:draper gem装饰STI模型

时间:2012-08-10 11:30:28

标签: ruby-on-rails-3 decorator draper

我有STI模型

#a/m/document.rb
class Document < ActiveRecord::Base
end

#a/m/document/static.rb
class Document::Static < Document
end

#a/m/document/dynamic.rb
class Document::Dynamic < Document
end

我正在使用draper gem来装饰我的模型

# a/d/document_decorator.rb
class DocumentDecorator <  ApplicationDecorator
end

 # a/d/document/static_decorator.rb
 class Document::StaticDecorator < DocumentDecorator
   def foo
     'it works 1'
   end
 end


 # a/d/document/dynamic_decorator.rb
 class Document::DynamicDecorator < DocumentDecorator
   def foo
     'it works 2'
   end
 end

有没有方法告诉draper用自己的STI类装饰器自动装饰模型?像这样:

a = Document.last   #<Document::Static ...
a.type              #Document::Static
b = DocumentDecorator.decorate(a)
b.class             # Document::StaticDecorator
b.foo               # "it works 1"

1 个答案:

答案 0 :(得分:0)

我发现我可以做的只是

resource.decorate

它将找到propriet decorator

a = Document.last   #<Document::Static ...
a.type              #Document::Static
b = a.decorate          
b.class             # Document::StaticDecorator

如果您需要使用文档装饰器显式装饰对象,请执行此操作

a = Document.last   #<Document::Static ...
a.type              #Document::Static
b = DocumentDecorator.decorate a
b.class             # DocumentDecorator