Module: CustomFields::Types::Money::Target::ClassMethods

Defined in:
lib/custom_fields/types/money.rb

Instance Method Summary collapse

Instance Method Details

#apply_money_custom_field(klass, rule) ⇒ Object

Adds a Money field

uses the money gem (github.com/RubyMoney/money)

if allow_currency_from_symbol is set the formatted_name_field will return the amount and the currency

Parameters:

  • klass (Class)

    The class to modify

  • rule (Hash)

    It contains the name of the field and if it is required or not



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/custom_fields/types/money.rb', line 55

def apply_money_custom_field(klass, rule)
  # the field names
  name = rule['name']
  names = {
    name: name.to_sym,
    cents_field: "#{name}_cents".to_sym,
    currency_field: "#{name}_currency".to_sym,
    formatted_name_field: "formatted_#{name}".to_sym,
    allow_currency_from_symbol: "#{name}_allow_currency_from_symbol".to_sym,
    default_currency: "#{name}_default_currency".to_sym
  }

  # fields
  klass.field names[:cents_field],    type: ::Integer, localize: false
  klass.field names[:currency_field], type: ::String,  localize: false

  # getters and setters
  klass.send(:define_method, name) { _get_money(names) }
  klass.send(:define_method, :"#{name}=") { |value| _set_money(value, names) }

  klass.send(:define_method, names[:formatted_name_field]) { _get_formatted_money(names) }
  klass.send(:define_method, :"#{names[:formatted_name_field]}=") { |value| _set_money(value, names) }

  klass.send(:define_method, names[:allow_currency_from_symbol]) { rule['allow_currency_from_symbol'] }
  klass.send(:define_method, names[:default_currency]) { rule['default_currency'] }

  # validations
  klass.validate { _check_money(names) } if rule['required']
  klass.validates_presence_of(names[:cents_field], names[:currency_field]) if rule['required']
  klass.validates_numericality_of names[:cents_field], only_integer: true, if: names[:cents_field]
end

#money_attribute_get(instance, name) ⇒ Object



87
88
89
90
91
92
93
# File 'lib/custom_fields/types/money.rb', line 87

def money_attribute_get(instance, name)
  if value = instance.send(:"formatted_#{name}")
    { name => value, "formatted_#{name}" => value }
  else
    {}
  end
end

#money_attribute_set(instance, name, attributes) ⇒ Object



95
96
97
98
99
100
# File 'lib/custom_fields/types/money.rb', line 95

def money_attribute_set(instance, name, attributes)
  return unless attributes.key?(name) || attributes.key?("formatted_#{name}")

  value = attributes[name] || attributes["formatted_#{name}"]
  instance.send(:"formatted_#{name}=", value)
end