Skip to content

Instantly share code, notes, and snippets.

@aalin
Forked from henrik/t_scope.rb
Last active December 11, 2015 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalin/4606043 to your computer and use it in GitHub Desktop.
Save aalin/4606043 to your computer and use it in GitHub Desktop.
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)
t_scoped_class = Struct.new(:scope) do
def t(key, opts = {})
I18n.t(key, opts.merge(scope: scope))
end
end
yield t_scoped_class.new(scope)
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