如何在我的应用程序中实现装饰器?

时间:2013-05-07 20:57:58

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

我正在尝试在我的应用中实施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(因为它的价值,我的piggybak_cart.rb文件夹中没有app/models/。)

我尝试运行rails g decorator Cart但这不起作用。

我所做的是将上述代码放在app/helpers/cart_helper.rb

然后,当我尝试运行rails g command(其他内容)时,我现在收到此错误:

/.rvm/gems/ruby-2.0.0-p0@myapp/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:230:in `block in constantize': uninitialized constant CartHelper (NameError)
    from /.rvm/gems/ruby-2.0.0-p0@myapp/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `each'
    from /.rvm/gems/ruby-2.0.0-p0@myapp/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `constantize'
    from /.rvm/gems/ruby-2.0.0-p0@myapp/gems/activesupport-3.2.13/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'
    from /.rvm/gems/ruby-2.0.0-p0@myapp/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:136:in `block in modules_for_helpers'
    from /.rvm/gems/ruby-2.0.0-p0@myapp/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:131:in `map!'

最好的方法是什么?

1 个答案:

答案 0 :(得分:3)

您应将以上代码添加到app/decorators/cart_decorator.rb

decorators文件夹将是新的,并在您启动rails应用程序时自动加载。当它运行Piggybak::Cart.send(:include, CartDecorator)时,它将使用您在上面声明的方法装饰您的Piggybag :: Cart。