Module: Amountable::ClassMethod

Defined in:
lib/amountable.rb

Instance Method Summary collapse

Instance Method Details

#allowed_amount_name?(name) ⇒ Boolean

Returns:

  • (Boolean)


109
110
111
# File 'lib/amountable.rb', line 109

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

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



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/amountable.rb', line 93

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

  define_method name do
    (find_amount(name) || Amountable::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



85
86
87
88
89
90
91
# File 'lib/amountable.rb', line 85

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

#pg_json_field_access(name, field = :cents) ⇒ Object



139
140
141
142
143
144
145
146
147
# File 'lib/amountable.rb', line 139

def pg_json_field_access(name, field = :cents)
  name = name.to_sym
  group = if name.in?(self.amount_names)
    'amounts'
  elsif name.in?(self.amount_sets.keys)
    'sets'
  end
  "#{self.amounts_column_name}::json#>'{#{group},#{name},#{field}}'"
end

#where(opts, *rest) ⇒ Object



113
114
115
116
117
118
119
120
# File 'lib/amountable.rb', line 113

def where(opts, *rest)
  return super unless opts.is_a?(Hash)
  if self.storage == :jsonb
    where_json(opts, *rest)
  else
    super
  end
end

#where_json(opts, *rest) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/amountable.rb', line 122

def where_json(opts, *rest)
  values = []
  query = opts.inject([]) do |mem, (column, value)|
    column = column.to_sym
    if column.in?(self.amount_names) || column.in?(self.amount_sets.keys)
      mem << "#{self.pg_json_field_access(column, :cents)} = '%s'"
      mem << "#{self.pg_json_field_access(column, :currency)} = '%s'"
      values << value.to_money.fractional
      values << value.to_money.currency.iso_code
      opts.delete(column)
    end
    mem
  end
  query = [query.join(' AND ')] + values
  where(query, *rest).where(opts, *rest)
end