Sha256: 65ca472ec642cabd2f2f8a2075458fb25457f21944aaf5b216dc7e363e7c3d0f

Contents?: true

Size: 1006 Bytes

Versions: 122

Compression:

Stored size: 1006 Bytes

Contents

require_dependency 'spree/calculator'

module Spree
  class Calculator::TieredFlatRate < Calculator
    preference :base_amount, :decimal, default: 0
    preference :tiers, :hash, default: {}

    before_validation do
      # Convert tier values to decimals. Strings don't do us much good.
      if preferred_tiers.is_a?(Hash)
        self.preferred_tiers = Hash[*preferred_tiers.flatten.map(&:to_f)]
      end
    end

    validate :preferred_tiers_content

    def self.description
      Spree.t(:tiered_flat_rate)
    end

    def compute(object)
      base, amount = preferred_tiers.sort.reverse.detect { |b, _| object.amount >= b }
      amount || preferred_base_amount
    end

    private

    def preferred_tiers_content
      if preferred_tiers.is_a? Hash
        unless preferred_tiers.keys.all? { |k| k.is_a?(Numeric) && k > 0 }
          errors.add(:base, :keys_should_be_positive_number)
        end
      else
        errors.add(:preferred_tiers, :should_be_hash)
      end
    end
  end
end

Version data entries

122 entries across 122 versions & 1 rubygems

Version Path
spree_core-4.10.1 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.10.0 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.9.0 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.8.3 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.8.2 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.7.3 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.6.6 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.5.5 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.0.9 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.1.15 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.2.7 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.3.3 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.4.1 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.5.4 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.6.5 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.7.2 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.7.1 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.6.4 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.7.0 app/models/spree/calculator/tiered_flat_rate.rb
spree_core-4.6.3 app/models/spree/calculator/tiered_flat_rate.rb