Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mkon/d12n
Very basic attribute delocalization
https://github.com/mkon/d12n
Last synced: 24 days ago
JSON representation
Very basic attribute delocalization
- Host: GitHub
- URL: https://github.com/mkon/d12n
- Owner: mkon
- License: mit
- Created: 2017-11-09T16:53:42.000Z (almost 7 years ago)
- Default Branch: main
- Last Pushed: 2024-03-12T23:50:07.000Z (8 months ago)
- Last Synced: 2024-03-15T10:11:47.454Z (8 months ago)
- Language: Ruby
- Size: 54.7 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# D12n
[![Gem Version](https://badge.fury.io/rb/d12n.svg)](https://badge.fury.io/rb/d12n)
[![Push & PR](https://github.com/mkon/d12n/actions/workflows/main.yml/badge.svg)](https://github.com/mkon/d12n/actions/workflows/main.yml)D12n (=delocalization) can be used to cast model attributes from localized format to an internal BigDecimal or Integer
representation. This is done by adding an additional attribute to the model which keeps the original value the user has
entered. This has the advantage that the original user input can be validated and rendered back to the user during
validation errors.## Usage
```ruby
gem 'd12n'
```Sample model
```ruby
class Dummy
include D12n::ModelSupportattr_accessor :amount
d12n_attribute :amount
end
``````ruby
d = Dummy.newd.amount = 1_234.56
d.local_amount # "1,234.56"d.local_amount = '3,456.78'
d.amount.class # BigDecimal
d.amount.to_f # 3456.78d.local_amount = 'invalid'
d.amount.to_f # 3456.78, did not change
```## Configuration
```ruby
# the default, no need to set it
# It will use the settings from your I18n locale (number.format) to parse and generate the formatted number
# It is heavily recommended to use this
D12n.config.strategy = D12n::Strategy::Default# Hard coded strategy using decimal point
D12n.config.strategy = D12n::Strategy::DecimalPoint# Hard coded strategy using decimal comma
D12n.config.strategy = D12n::Strategy::DecimalComma
```### Custom method prefix
```ruby
d12n_attribute :amount, prefix: 'localized'
```Would give you `localized_amount` instead of `local_amount`.
### Internal integer representation with a factor
If your internal representation is for example in cents, but the local format should be EUR with decimal point
you can use this option:```ruby
d12n_attribute :amount, factor: 100
``````ruby
d = Dummy.newd.amount = 1_234
d.local_amount # "12,34"d.local_amount = '3,456.78'
d.amount.class # Integer
d.amount # 345_678
```