【问题标题】:Is it possible to add new methods inside in a child ShippingCalculator custom class in Spree?是否可以在 Spree 的子 ShippingCalculator 自定义类中添加新方法?
【发布时间】:2023-07-26 03:05:01
【问题描述】:

我创建了一个名为CorreiosPAC 的新自定义类,它计算订单的包裹成本和交货时间(订单的截止日期)(请看下面的代码)。我在 ShippingRate 模型中添加了一个名为 delivery_time 的新字段来存储交货时间。但是,我无法保存此值以在视图中显示给客户端。这是我最初想到的解决方案。我需要一个最好的解决方案,一个模式解决方案,我不知道该怎么做。

models/calculator/shipping/correios_pac.rb

require 'correios-frete'

module Spree
  module Calculator::Shipping

    class CorreiosPAC < ShippingCalculator
      attr_reader :delivery_time

      def self.description
        # Human readable description of the calculator
        'Entrega Econômica (PAC)'
      end

      def compute_package(package)
        # Returns the value after performing the required calculation

        altura = package.quantity * 2 + 1
        peso = (200.0 * package.quantity) / 1000 + 0.2
        cep_origem = '65086-110'
        cep_destino = package.order.shipping_address.zipcode

        @frete = Correios::Frete::Calculador.new( :cep_origem => cep_origem,
          :cep_destino => cep_destino,
          :peso => peso,
          :comprimento => 30,
          :largura => 30,
          :altura => altura).calcular :pac

        @delivery_time = @frete.prazo_entrega
        @frete.valor
      end
    end

  end
end

models/shipping_rate_decorator.rb

Spree::ShippingRate.class_eval do
  attr_accessor :delivery_time 
end

【问题讨论】:

    标签: ruby-on-rails ruby spree


    【解决方案1】:

    您不应将交货时间存储在计算器中,因为它用于计算运费。

    地址转换完成后,可以直接按顺序调用并存储远程api Correios::Frete::Calculador(需要迁移)。

    然后你可以在计算器中从包中访问订单对象:

    def compute_package(package)
    ...
    package.order.frete.valor
    ...
    end
    

    【讨论】:

      最近更新 更多