Last active
October 15, 2015 12:33
-
-
Save brodock/3feb24b0c6b69e89d5e0 to your computer and use it in GitHub Desktop.
Money Attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍 ⭐