Module: Picklive::Currency::Converters

Defined in:
lib/picklive/currency.rb

Overview

Provides setters and getters for ‘something_in_currency`, alias: `something` Mix it into classes that have `something_in_pennies` setter/getter and call:

cuurrency_field :something

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/picklive/currency.rb', line 157

def self.included(base)
  base.instance_eval do
    def currency_field(*fields)
      self.class_eval do

        fields.each do |field|
          define_method "#{field}_in_currency" do
            pennies = self.send("#{field}_in_pennies")
            currency.new(pennies) unless pennies.nil?
          end

          define_method "#{field}_in_currency=" do |amount_in_currency|
            if ! amount_in_currency.is_a?(Picklive::Currency::Base)
              amount_in_currency = Picklive::Currency::GBP.new((amount_in_currency.to_f * Picklive::Currency::GBP.precision).round)
            end
            if self.respond_to?("currency_code=")
              self.currency_code = amount_in_currency.class.code
            end
            self.send("#{field}_in_pennies=", amount_in_currency.integer_amount)
          end

          alias_method :"#{field}",  :"#{field}_in_currency"
          alias_method :"#{field}=", :"#{field}_in_currency="

        end
      end
    end

    def currency_fields(*fields)
      currency_field(*fields)
    end
  end
end