首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 3: draper gem装饰STI模型

Rails 3: draper gem装饰STI模型
EN

Stack Overflow用户
提问于 2012-08-10 19:30:28
回答 1查看 1.5K关注 0票数 0

我有STI模型

代码语言:javascript
复制
#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来装饰我的模型

代码语言:javascript
复制
# 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类装饰器自动装饰模型?如下所示:

代码语言:javascript
复制
a = Document.last   #<Document::Static ...
a.type              #Document::Static
b = DocumentDecorator.decorate(a)
b.class             # Document::StaticDecorator
b.foo               # "it works 1"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-22 18:26:09

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

代码语言:javascript
复制
resource.decorate

它会找到专属的装饰者

代码语言:javascript
复制
a = Document.last   #<Document::Static ...
a.type              #Document::Static
b = a.decorate          
b.class             # Document::StaticDecorator

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

代码语言:javascript
复制
a = Document.last   #<Document::Static ...
a.type              #Document::Static
b = DocumentDecorator.decorate a
b.class             # DocumentDecorator
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11900754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档