Last active
July 31, 2024 12:05
-
-
Save glaucocustodio/8481b648d2d5dd01c258252a29d67aff to your computer and use it in GitHub Desktop.
brazilian currency formating (Ruby on Rails - attributes api)
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
# 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 |
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
# 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 |
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
# 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 |
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
# 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