Sha256: 463d4debf7929ad71a6b5efb711e66310291425b3285fe7ae449049175e30319

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

class PriceType
  include EnumField::DefineEnum

  attr_reader :code, :range

  def initialize(code, range)
    @code = code.to_sym
    @range = range
  end

  def title
    I18n.t(code, scope: [:price_type])
  end

  def calc(price, options = {})
    send("calc_#{code}", price, options)
  end

  def calc_static(price, _options)
    price
  end

  def calc_percentage(price, options)
    (options[:base].to_f * price.to_f) / 100.0
  end

  def calc_percentage_min_amount(price, options)
    checkpoint = options[:checkpoint_amount]
    checkpoint ||= (options[:min_amount] * 100.0 / price.to_f)

    if checkpoint >= options[:base].to_f
      options[:min_amount]
    else
      calc_percentage(price, options)
    end
  end

  def percentage?
    [:percentage, :percentage_min_amount].include?(code)
  end

  def format(value)
    price = value.to_f.round(2)

    case @code
    when :static then "$#{price}"
    when :percentage, :percentage_min_amount then "#{price}%"
    end
  end

  define_enum do |builder|
    builder.member :static, object: new(:static, 0..10_000)
    builder.member :percentage, object: new(:percentage, 0..100)
    builder.member :percentage_min_amount, object: new(:percentage_min_amount, 0..100)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
translation_cms-0.1.5 app/models/enums/price_type.rb