Hi,
I am having some trouble finding out how best to use ruby-gettext in my
app. I do this in my ApplicationController:
before_filter :localize
private
def localize
# we will always use UTF-8
@charset = ''utf-8''
@headers["Content-Type"] = "text/html; charset=@charset"
# simplified approach: extract the first language from the request
# or use en
temp
@request.env[''HTTP_ACCEPT_LANGUAGE''].split('','').first.split(''-'')
language = temp.slice(0)
dialect = temp.slice(1)
@language = language.nil? ? ''en'' : language.downcase #
default is en
@dialect = dialect.nil? ? language : dialect
# should always produce language_DIALECT (en_EN, en_GB, de_DE, ...)
@locale = "#{language}_#{dialect.upcase}"
ENV[''LC_MESSAGES''] = ENV[''LANG''] =
@locale
Locale.set(Locale::MESSAGES, @locale)
@gettext = bindtextdomain(''messages'',
"#{RAILS_ROOT}/locale",
@locale, @charset)
# after this, i can call _(''Cancel'') in the controller and
this will
# return => "Abbrechen" for de_DE (German)
end
I want to be able to use _() everywhere, so I have a
lib/gettext_extension.rb file that says:
require ''gettext''
include GetText # we want to be able to translate everywhere
Nevertheless, I cannot use _() anywhere but in the controller. If I want
to use it in say editor.rhtml I have to do this:
# app/views/blocks/editor.rhtml:
<% bindtextdomain(''messages'',
"#{RAILS_ROOT}/locale", @locale, @charset) %>
This is true for any view and partial, meaning I have to do it in
app/views/block/page_versions.rhtml, too, if I want the strings to get
translated in there.
I had a workaround which worked nicely, but is hardly the right way to
do it. In ApplicationHelper i had:
def _(text)
bindtextdomain(''messages'', "#{RAILS_ROOT}/locale",
@locale, @charset)
GetText._(text)
end
bindtextdomain should only be called once on initialization and than
cached for every language. I want to select the language based on the
current request.
Is there anyone out there already using Gettext for localization? If
yes, how do you do it?
Sascha Ebach
PS: I know of the MLL project, but I want to be able to use gettext
tools to work with the language files (MLL uses YAML to store the
strings not the native PO/MO format). MLL extends the the Base classes
of ActionView for example, but I want to be able to translate everything
in the application, so also error messages in the model and messages in
custom files that are in the lib dir, etc.