Micael
Micael

Reputation: 81

Is it possible to add new methods inside in a child ShippingCalculator custom class in Spree?

I created a new custom class called CorreiosPAC thats computes a cost of package and the delivery time (order's deadline) for a order (look the code below). I added a new field called delivery_time in ShippingRate model to store the delivery time. But, I can't save this value to show to the client in the view. This was the initial solution I thought. I need a best solution for this, a pattern solution spree, which I don't know how to do.

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

Upvotes: 1

Views: 78

Answers (1)

Renaud Kern
Renaud Kern

Reputation: 1156

You should not store the delivery time in the Calculator as it used for computing shipping amount.

You can call and store the remote api Correios::Frete::Calculador in the order directly (migration needed) after the address transition is completed.

Then you can access order object from the package in Calculator :

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

Upvotes: 1

Related Questions