0

我有 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"
4

1 回答 1

0

花了我一段时间才发现我可以做到

resource.decorate

它会找到合适的装饰器

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

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

a = Document.last   #<Document::Static ...
a.type              #Document::Static
b = DocumentDecorator.decorate a
b.class             # DocumentDecorator
于 2012-08-22T10:26:09.287 回答