Module: Amountable::ClassMethod

Defined in:
lib/amountable.rb

Instance Method Summary collapse

Instance Method Details

#allowed_amount_name?(name) ⇒ Boolean

Returns:

  • (Boolean)


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

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

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



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

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



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

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



142
143
144
145
146
147
148
149
150
# File 'lib/amountable.rb', line 142

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



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

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



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

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