Created
June 24, 2014 20:45
-
-
Save yannvery/3ab52da8a79abdb9555a to your computer and use it in GitHub Desktop.
How to create BigDecimal with comma ?
The problem is that BigDecimal ignores everything to the right of the first comma.
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
| #Another elegant solution source : http://chris.finne.us/2011/07/22/ruby-rails-initialize-bigdecimal-with-commas-in-the-string/ | |
| class BigDecimal | |
| class << self | |
| def new_with_commas(*args) | |
| if args.first.is_a?(String) && args.first=~/,/ | |
| args.first.gsub!(',','') | |
| end | |
| new_without_commas(*args) | |
| end | |
| alias_method_chain :new, :commas | |
| 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
| class Sample < ActiveRecord::Base | |
| #Create an arrayt that contains all BigDecimal fields | |
| FLOATING_ATTRIBUTES = %w(price quantity tva_rate) | |
| #Overcharge '=' method and sub all ',' with '.' | |
| FLOATING_ATTRIBUTES.each do |attr| | |
| define_method "#{attr}=" do |p| | |
| self[attr.to_sym] = p.gsub(",", ".") | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment