Sha256: 4f8821f361c40ad3e287e1f59a41005428ac2f63284c7bad7e88e20378bd8f40

Contents?: true

Size: 1.69 KB

Versions: 6

Compression:

Stored size: 1.69 KB

Contents

module Spree
  class Price < Spree::Base
    acts_as_paranoid
    belongs_to :variant, class_name: 'Spree::Variant', inverse_of: :prices, touch: true

    validate :check_price
    validates :amount, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
    validate :validate_amount_maximum

    def display_amount
      money
    end
    alias :display_price :display_amount

    def money
      Spree::Money.new(amount || 0, { currency: currency })
    end

    def price
      amount
    end

    def price=(price)
      self[:amount] = parse_price(price)
    end

    # Remove variant default_scope `deleted_at: nil`
    def variant
      Spree::Variant.unscoped { super }
    end

    private

    def check_price
      raise "Price must belong to a variant" if variant.nil?

      if currency.nil?
        self.currency = Spree::Config[:currency]
      end
    end

    # strips all non-price-like characters from the price, taking into account locale settings
    def parse_price(price)
      return price unless price.is_a?(String)

      separator, delimiter = I18n.t([:'number.currency.format.separator', :'number.currency.format.delimiter'])
      non_price_characters = /[^0-9\-#{separator}]/
      price.gsub!(non_price_characters, '') # strip everything else first
      price.gsub!(separator, '.') unless separator == '.' # then replace the locale-specific decimal separator with the standard separator if necessary

      price.to_d
    end

    def maximum_amount
      BigDecimal '999999.99'
    end

    def validate_amount_maximum
      if amount && amount > maximum_amount
        errors.add :amount, I18n.t('errors.messages.less_than_or_equal_to', count: maximum_amount)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spree_core-2.4.0.rc3 app/models/spree/price.rb
spree_core-2.4.0.rc2 app/models/spree/price.rb
spree_core-2.4.0.rc1 app/models/spree/price.rb
spree_core-2.3.4 app/models/spree/price.rb
spree_core-2.3.3 app/models/spree/price.rb
spree_core-2.3.2 app/models/spree/price.rb