Sha256: 10a8f2e7e54fc894263c61e9df85dd82fbcdd7e2c7b99121801191ab80a9c141

Contents?: true

Size: 965 Bytes

Versions: 2

Compression:

Stored size: 965 Bytes

Contents

module MoneyField

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    # Add a money field attribute
    #
    # By default it will use attribute_in_cents for cents value
    def money_field(attribute)
      module_eval <<-METHOD
        def #{attribute}
          Money.new(#{attribute}_in_cents) if #{attribute}_in_cents.present?
        end

        # Allow assigning of non money objects directly
        # Allows form data to be directly passed through
        # e.g. object.cost = '5.1'
        def #{attribute}=(money)
          self.#{attribute}_in_cents = money.try(:to_money).try(:cents)
        end
      METHOD
    end


    def money_fields(*attributes)
      attributes.each {|a| self.money_field(a)}
    end


    def money(*fields)
      fields.each do |field|
        class_eval <<-METHOD
          def #{field}
            Money.new(#{field}_in_cents)
          end
        METHOD
      end
    end

  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
money_extensions-0.1.0 lib/money_extensions/money_field.rb
money_extensions-0.0.2 lib/money_extensions/money_field.rb