Skip to content

Commit

Permalink
Implement I18n::Alchemy#unlocalize to return the original target
Browse files Browse the repository at this point in the history
  • Loading branch information
sobrinho committed Apr 29, 2019
1 parent 6dde860 commit ba98836
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## master

* Add unlocalize to get the original target ([@sobrinho](https://github.com/sobrinho))

## v0.3.0 - 2018-09-08

* Update I18n dependency to require >= 0.7, allowing to install more recent versions ([@nazarhussain](https://github.com/nazarhussain))
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,18 @@ I18n.with_locale :pt do
end
```

Keep in mind that `product.localized` is a proxy object and if you need the original value, you need either to use the original object or unlocalize the proxy for action view helpers like `date_select`:

```ruby
# In case you have the original target.
f.date_select :released_at, selected: @product.released_at

# In case you don't have the original target, you can use `unlocalize` to get it back.
f.date_select :released_at, selected: @localized.unlocalize.released_at
```

This is necessary because such Rails helpers expects a Date/Time object and not a localized string.

### Localizing methods

Given a product model with a `total` method, that is a simple calculation of `quantity * price`, you can tell **I18n::Alchemy** to localize that method for you together with the attributes:
Expand Down
6 changes: 6 additions & 0 deletions lib/i18n_alchemy/proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ def initialize(target, attributes = nil)
assign_attributes(attributes) if attributes
end

# Returns the original target. This is useful for action view helpers that
# expects the unlocalized value like a +Date+ or +Time+.
def unlocalize
@target
end

# Override to_param to always return the +proxy.to_param+. This allow us
# to integrate with action view.
def to_param
Expand Down
4 changes: 4 additions & 0 deletions test/i18n_alchemy/proxy_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
require "test_helper"

class ProxyTest < I18n::Alchemy::ProxyTestCase
def test_unlocalize
assert_equal @product, @localized.unlocalize
end

def test_delegates_orm_methods_to_target_object
assert @product.new_record?
assert @localized.save!(:name => "foo", :price => 1.99)
Expand Down

0 comments on commit ba98836

Please sign in to comment.