Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active December 11, 2015 13:08
Show Gist options
  • Save henrik/4605425 to your computer and use it in GitHub Desktop.
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).
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
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