Making ActionController::Translation#translate more like ActionView::Helpers::TranslationHelper#translate
I started using i18n support in rails. I really liked how the ActionView::Helpers::TranslationHelper#translate method works.
If the key starts with “.”, then the key is scoped to the partial. For example, if translate(”.title”) is called from the registrations/new page, then the key gets scoped to ‘registrations.new.title’. I wanted the same sort of behavior with the ActionController::Translation#translate, so I created my own method called scope_key_by_controller_and_action and placed it in the ApplicationController. The code looks like:
def scope_key_by_controller_and_action( key )
return key unless key.first == "."
"#{controller_name}.#{action_name}#{key}"
end
Then I could use it with the ActionController::Translation#translate method, like so:
def page_title
@page_title ||=
t( scope_key_by_controller_and_action(".title") )
end
The scope_key_by_controller_and_action(”.title”) will be converted to “registrations.new.title” for a controller/action combo of “registrations” and “new”. If the key doesn’t start with “.” then the original key is returned.