I'm new to Rails/Ruby and I would like to get feedback on my little ApplicationController
which is able to detect the visitor's language. I'm especially interested in optimizations on the control structure in the set_locale
method (2 nested if
statements and 3 assignments to one variable). I'm using the http_accept_language gem.
class ApplicationController < ActionController::Base
AVAILABLE_LANGUAGES = %w{de en}
before_filter :set_locale
protect_from_forgery
def set_locale
if params[:locale].nil?
if preferred_language = request.preferred_language_from(AVAILABLE_LANGUAGES)
I18n.locale = preferred_language
else
I18n.locale = I18n.default_locale
end
else
I18n.locale = params[:locale]
end
end
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{ :locale => I18n.locale }
end
end
true
. Checking forparams[:local].empty?
is better thannil?
sincenil?
returns false for empty strings, and the locale can be an empty string. \$\endgroup\$"" == true => false
\$\endgroup\${foo: ''}[:foo].nil? => false
\$\endgroup\$