From 5844932193802d7b191a8c5bf56bc4b69f89a616 Mon Sep 17 00:00:00 2001 From: Gabriel Sobrinho Date: Mon, 29 Apr 2019 15:34:27 -0300 Subject: [PATCH] Implement I18n::Alchemy#unlocalize to return the original target Closes #39 --- CHANGELOG.md | 4 ++++ README.md | 12 ++++++++++++ lib/i18n_alchemy/proxy.rb | 6 ++++++ test/i18n_alchemy/proxy_test.rb | 4 ++++ 4 files changed, 26 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 116774e..17d8ed1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)) diff --git a/README.md b/README.md index 005c304..0d13259 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/lib/i18n_alchemy/proxy.rb b/lib/i18n_alchemy/proxy.rb index 323398a..d9cca2b 100644 --- a/lib/i18n_alchemy/proxy.rb +++ b/lib/i18n_alchemy/proxy.rb @@ -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 diff --git a/test/i18n_alchemy/proxy_test.rb b/test/i18n_alchemy/proxy_test.rb index 1edfcf0..5b4ec70 100644 --- a/test/i18n_alchemy/proxy_test.rb +++ b/test/i18n_alchemy/proxy_test.rb @@ -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)