Module: Amountable::ClassMethods

Defined in:
lib/amountable.rb

Instance Method Summary collapse

Instance Method Details

#act_as_amountable(options = {}) ⇒ Object

Possible storage values: [:table, :jsonb]



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/amountable.rb', line 64

def act_as_amountable(options = {})
  case (options[:storage] || :table).to_sym
  when :table
    has_many :amounts, as: :amountable, dependent: :destroy, autosave: false
    include Amountable::TableMethods
  when :jsonb
    self.amounts_column_name = options[:column].to_s if options[:column]
    raise MissingColumn.new("You need an amounts jsonb field on the #{self.table_name} table.") unless column_names.include?(self.amounts_column_name)
    include Amountable::JsonbMethods
  else
    raise ArgumentError.new("Please specify a storage: #{ALLOWED_STORAGE}")
  end
end

#allowed_amount_name?(name) ⇒ Boolean

Returns:

  • (Boolean)


102
103
104
# File 'lib/amountable.rb', line 102

def allowed_amount_name?(name)
  self.amount_names.include?(name.to_sym)
end

#amount(name, options = {}) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/amountable.rb', line 86

def amount(name, options = {})
  (self.amount_names ||= Set.new) << name

  define_method name do
    (find_amount(name) || ::NilAmount.new).value
  end

  define_method "#{name}=" do |value|
    set_amount(name, value)
  end

  Array(options[:summable] || options[:summables] || options[:set] || options[:sets] || options[:amount_set] || options[:amount_sets]).each do |set|
    amount_set(set, name)
  end
end

#amount_set(set_name, component) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/amountable.rb', line 78

def amount_set(set_name, component)
  self.amount_sets[set_name.to_sym] << component.to_sym

  define_method set_name do
    get_set(set_name)
  end
end