如何在我的应用程序中实现装饰器?
问题描述:
我想在我的应用程序中实现this。如何在我的应用程序中实现装饰器?
这篇文章说我必须创建一个装饰器 - 但它没有详细说明如何做到这一点。这是代码:
module CartDecorator
extend ActiveSupport::Concern
module InstanceMethods
def is_downloadable?
items = self.items.collect { |li| li[:variant].item }
items.all? { |i| i.is_downloadable }
end
def has_downloadable?
items = self.items.collect { |li| li[:variant].item }
items.any? { |i| i.is_downloadable }
end
end
end
Piggybak::Cart.send(:include, CartDecorator)
我不知道我是否应该该代码添加到一些model.rb
(对于它的价值,我不会在我的app/models/
文件夹中有一个piggybak_cart.rb
做)。
我试着运行rails g decorator Cart
,但没有奏效。
我所做的是把上面的代码放在app/helpers/cart_helper.rb
。
然后,当我试图运行一个rails g command
(别的东西),我现在收到此错误:
/.rvm/gems/[email protected]/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:230:in `block in constantize': uninitialized constant CartHelper (NameError)
from /.rvm/gems/[email protected]/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `each'
from /.rvm/gems/[email protected]/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `constantize'
from /.rvm/gems/[email protected]/gems/activesupport-3.2.13/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'
from /.rvm/gems/[email protected]/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:136:in `block in modules_for_helpers'
from /.rvm/gems/[email protected]/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:131:in `map!'
什么是接近最好的方法?
答
您应该添加上面的代码为app/decorators/cart_decorator.rb
的装饰文件夹将是新的,当您启动的Rails应用程序自动载入。当它运行Piggybak::Cart.send(:include, CartDecorator)
它会用上面声明的方法来装饰你的Piggybag :: Cart。
非常感谢。正是医生要求的:) – marcamillion 2013-05-07 21:19:52