Module: Amountable

Extended by:
ActiveSupport::Autoload
Defined in:
lib/amountable.rb,
lib/amountable/version.rb

Overview

Copyright 2015, Instacart

Defined Under Namespace

Modules: ClassMethods Classes: InvalidAmountName

Constant Summary collapse

VERSION =
'0.0.7'

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/amountable.rb', line 10

def self.included(base)

  base.extend Amountable::ClassMethods

  base.class_eval do
    has_many :amounts, as: :amountable, dependent: :destroy, autosave: false
    validate :validate_amount_names
    class_attribute :amount_names
    class_attribute :amount_sets
    self.amount_sets = Hash.new { |h, k| h[k] = Set.new }
    self.amount_names = Set.new

    def all_amounts
      @all_amounts ||= amounts.to_set
    end

    def find_amount(name)
      (@amounts_by_name ||= {})[name.to_sym] ||= all_amounts.find { |am| am.name == name.to_s }
    end

    def find_amounts(names)
      all_amounts.select { |am| names.include?(am.name.to_sym) }
    end

    def validate_amount_names
      amounts.each do |amount|
        errors.add(:amounts, "#{amount.name} is not an allowed amount name.") unless self.class.allowed_amount_name?(amount.name)
      end
    end

    def serializable_hash(opts = nil)
      opts ||= {}
      super(opts).tap do |base|
        unless opts[:except].to_a.include?(:amounts)
          amounts_json = (self.class.amount_names + self.class.amount_sets.keys).inject({}) do |mem, name|
            mem.merge!(name.to_s => send(name).to_f) unless opts[:except].to_a.include?(name.to_sym)
            mem
          end
          base.merge!(amounts_json)
        end
      end
    end

    def save(args = {})
      ActiveRecord::Base.transaction do
        save_amounts if super(args)
      end
    end

    def save!(args = {})
      ActiveRecord::Base.transaction do
        save_amounts! if super(args)
      end
    end

    def save_amounts(bang: false)
      amounts_to_insert = []
      amounts.each do |amount|
        if amount.new_record?
          amount.amountable_id = self.id
          amounts_to_insert << amount
        else
          bang ? amount.save! : amount.save
        end
      end
      Amount.import(amounts_to_insert, timestamps: true, validate: false)
      amounts_to_insert.each do |amount|
        amount.instance_variable_set(:@new_record, false)
      end
      true
    end

    def save_amounts!; save_amounts(bang: true); end

  end
end