Module: CustomFields::Types::Money::Target::ClassMethods
- Defined in:
- lib/custom_fields/types/money.rb
Instance Method Summary collapse
-
#apply_money_custom_field(klass, rule) ⇒ Object
Adds a Money field.
- #money_attribute_get(instance, name) ⇒ Object
- #money_attribute_set(instance, name, attributes) ⇒ Object
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
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 86 87 88 |
# File 'lib/custom_fields/types/money.rb', line 56 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
90 91 92 93 94 95 96 |
# File 'lib/custom_fields/types/money.rb', line 90 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
98 99 100 101 102 |
# File 'lib/custom_fields/types/money.rb', line 98 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 |