Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active September 4, 2018 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glaucocustodio/8481b648d2d5dd01c258252a29d67aff to your computer and use it in GitHub Desktop.
Save glaucocustodio/8481b648d2d5dd01c258252a29d67aff to your computer and use it in GitHub Desktop.
brazilian currency formating (Ruby on Rails - attributes api)
# app/types/br_money_type.rb
class BrMoneyType < ActiveRecord::Type::Decimal
def cast(value)
value.is_a?(String) ? value.clean_money : value
end
def deserialize(value)
value ? value.to_f : value
end
end
# model.rb
attribute :value, :br_money
attribute :discount_value, :br_money
# console
# Model.create(value: '1.850,25', discount_value: 'R$ 5.300,89')
# Model.last.value => 1850.25
# Model.last.discount_value => 5300.89
# config/initializers/string_ext.rb
class String
# Convert a money string ('R$ 10.000,00') to float (10000.0)
def clean_money
self.gsub(/[^\d,]/, '').gsub(',', '.').strip.to_f
end
end
# config/initializers/types.rb
ActiveRecord::Type.register(:br_money, BrMoneyType)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment