Skip to content

Instantly share code, notes, and snippets.

@brodock
Last active October 15, 2015 12:33
Show Gist options
  • Save brodock/3feb24b0c6b69e89d5e0 to your computer and use it in GitHub Desktop.
Save brodock/3feb24b0c6b69e89d5e0 to your computer and use it in GitHub Desktop.
Money Attributes
module Financeiro
# Inclui suporte para escrever em um campo com valor monetário
# utilizando BigDecimal, ou valor em string seguindo sintaxe
# do jQuery MoneyMask
#
# Para habilitar em um model é preciso primeiro fazer um include no model:
# include MoneyAttribute
#
# Defina cada um dos campos que você quer que tenham o comportamento:
# money_attribute :field_name
module MoneyAttribute
def self.included(base)
base.send :extend, ClassMethods
end
protected
def write_money_attribute(attribute, value)
if value.is_a?(String)
value = value.gsub('.', '')
value = value.sub(',', '.')
value = BigDecimal.new(value)
end
write_attribute attribute.to_sym, value
end
module ClassMethods
protected
# Define um atributo como sendo do tipo money (decimal)
# Utilize somente dentro de um ActiveModel ou ActiveResource
# @param [Symbol] attribute
def money_attribute(attribute)
define_method "#{attribute}=" do |value|
write_money_attribute(attribute, value)
end
end
end
end
end
// Install maskmoney-rails gem
//= require maskmoney
$(document).ready(function() {
// Money input
initialize_money_input();
}
function initialize_money_input() {
$("input.money").maskMoney({thousands: '.', decimal: ','}).maskMoney('mask');
}
class MoneyInput < SimpleForm::Inputs::StringInput
include ActionView::Helpers::NumberHelper
def input
value = input_html_options[:value]
value ||= object.send(attribute_name) if object.respond_to? attribute_name
input_html_options[:value] = number_with_precision(value, precision: 2)
input_html_options[:type] = 'text'
super # leave StringInput do the real rendering
end
end
@brodock
Copy link
Author

brodock commented Jan 25, 2015

Para utilizar em um model:

class Bill < ActiveRecord::Base
  include Financeiro::MoneyAttribute

  money_attribute :value
end

@breim
Copy link

breim commented Jan 25, 2015

Nice bro.

@ramoncaldeira
Copy link

👍 ⭐

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment