Skip to content

Instantly share code, notes, and snippets.

@yannvery
Created June 24, 2014 20:45
Show Gist options
  • Select an option

  • Save yannvery/3ab52da8a79abdb9555a to your computer and use it in GitHub Desktop.

Select an option

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.
#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
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