Last active
December 11, 2015 13:08
-
-
Save henrik/4605425 to your computer and use it in GitHub Desktop.
Rails i18n t_scope method to use the same translation scope for multiple translations. Less noise if you prefer interpolation to inline markup (as you probably should).
This file contains 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
module I18n | |
# Usage (Haml in examples): | |
# | |
# - t_scope(:"public.sign_up_or_log_in") do |s| | |
# = simple_format(s.t(:text, | |
# sign_up: link_to(s.t(:sign_up), signup_path), | |
# log_in: link_to(s.t(:log_in), login_path))) | |
# | |
# is equivalent to | |
# | |
# = simple_format(t(:"public.sign_up_or_log_in.text", | |
# sign_up: link_to(t(:"public.sign_up_or_log_in.sign_up"), signup_path), | |
# log_in: link_to(t(:"public.sign_up_or_log_in.log_in"), login_path))) | |
# | |
# Note that you need to use "-" or it will render the string twice. | |
# | |
def self.t_scope(scope) | |
scoped = Object.new | |
scoped.define_singleton_method(:t) { |key, opts = {}| | |
I18n.t(key, opts.merge(scope: scope)) | |
} | |
yield(scoped) | |
end | |
end |
This file contains 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
describe I18n, ".t_scope(scope)" do | |
it "provides a scoping object" do | |
I18n.backend.store_translations(I18n.locale, { | |
foo: { | |
text: "Hello %{world}!", | |
world: "world" | |
} | |
}) | |
I18n.t_scope(:foo) { |s| s.t(:text, world: s.t(:world)) }.should == "Hello world!" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment