【问题标题】:Spree module decorator大礼包模块装饰器
【发布时间】:2013-07-23 12:42:21
【问题描述】:

我正在为我的网上商店使用 Spree Commerce。我想在结帐过程中更改一些行为,这是在 spree gem 内的app/models/spree/order/checkout.rb 中定义的。所以我在我的应用程序的同一点上创建了一个checkout_decorator.rb

问题是,我的更改没有加载。另一个问题是,模块内的所有内容都在一个方法中,即def self.included(klass) 方法。所以我认为我必须覆盖整个文件,而不仅仅是一种方法。这是我的装饰器的样子:

checkout_decorator.rb

Spree::Order::Checkout.module_eval do
  def self.included(klass)
    klass.class_eval do
      class_attribute :next_event_transitions
      class_attribute :previous_states
      class_attribute :checkout_flow
      class_attribute :checkout_steps

      def self.define_state_machine!
         # here i want to make some changes
      end

      # and the other methods are also include here
      # for readability, i don't show them here
    end
  end
end

来自 spree gem 的原始文件 checkout.rb 如下所示:

module Spree
  class Order < ActiveRecord::Base
    module Checkout
      def self.included(klass)
        klass.class_eval do
          class_attribute :next_event_transitions
          class_attribute :previous_states
          class_attribute :checkout_flow
          class_attribute :checkout_steps

          def self.checkout_flow(&block)
            if block_given?
              @checkout_flow = block
              define_state_machine!
            else
              @checkout_flow
            end
          end

          def self.define_state_machine!
             # some code
          end

          # and other methods that are not shown here
        end
      end
    end
  end
end

所以我的问题是:为什么这不起作用? module_eval 是正确的方法吗?我试过class_eval,但它也不起作用。我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    module_eval 方法对你不起作用。

    您应该查看Spree Checkout Flow Documentation,了解有关如何自定义结帐流程的一些很好的示例。这是自定义结帐流程的推荐方式,因为您无需复制/粘贴一大堆代码。

    【讨论】:

      【解决方案2】:

      命名空间不正确。

      试试Spree::Order::Checkout.class_eval do

      【讨论】:

        【解决方案3】:

        tl;dr:在 Spree::Order 类中覆盖您想要的方法,而不是 Spree::Order::Checkout 模块。

        您提到在原始文件 (spree_core-3.2.0.rc3/app/models/spree/order/checkout.rb) 中有一个包装整个模块的方法。

        def self.included(klass)
          klass.class_eval do
        

        当模块被包含在一个类中时,该方法被调用,并且它自己的class_eval 将模块的方法添加到包含它的类的实例中。

        所以既然 (spree_core-3.2.0.rc3/app/models/spree/order.rb) 有这一行:

        include Spree::Order::Checkout
        

        我们可以给订单类本身添加一个装饰器(app/models/spree/order_decorator.rb)

        【讨论】:

          猜你喜欢
          • 2016-06-04
          • 2012-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-09
          • 2017-08-15
          • 1970-01-01
          相关资源
          最近更新 更多