Module: Amountable

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

Overview

Copyright 2015-2016, Instacart

Defined Under Namespace

Modules: ClassMethods, JsonbMethods, TableMethods Classes: InvalidAmountName, MissingColumn

Constant Summary collapse

ALLOWED_STORAGE =
i(table json).freeze
VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
# File 'lib/amountable.rb', line 15

def self.included(base)

  base.extend Amountable::ClassMethods

  base.class_eval do
    validate :validate_amount_names
    class_attribute :amount_names
    class_attribute :amount_sets
    class_attribute :amounts_column_name
    self.amount_sets = Hash.new { |h, k| h[k] = Set.new }
    self.amount_names = Set.new
    self.amounts_column_name = 'amounts'

    def all_amounts
      @all_amounts ||= amounts.to_set
    end

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

    def find_amounts(names)
      amounts.to_set.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
  end
end