Search code examples
ruby-on-railsrubygemshttp-accept-language

Using http_accept_language gem on rails 3


I'm trying to use this gem to determine the user's preferred language, and running into some trouble.

undefined local variable or method http_accept_language for #<HomeController:0x964f5ec>

I included the gem in the Gemfile, ran bundle install, and restarted the server multiple times. Why doesn't my app recognize the gem?

Also, in my ApplicationController I wrote the following method:

def set_i18n_locale
 http_accept_language.user_preferred_languages
 available = %w{en kr}
 params[:locale] = http_accept_language.preferred_language_from(available)
    if params[:locale]
        I18n.locale = params[:locale]
    end
end

One thing I don't understand is the second line, http_accept_language.user_preferred_languages

From https://github.com/iain/http_accept_language, this is supposed to return a sorted array. I thought I had to store the array into some variable and use it, but the author just throws the method like that. How does that work? Can't I just do the following?

available = %w{en kr}
params[:locale] = http_accept_language.language_region_compatible_from(available)

I am just a little confused by the author's explanation.

Thank you for your help.

UPDATE: the gem, http_accept_language, doesn't seem to be installed successfully. It's on the gem list, but when I try to uninstall it, the error message shows that it's not installed. Why does this happen?

max@max-VirtualBox:~/appe$ gem list

*** LOCAL GEMS ***
...
http_accept_language (1.0.2)
...

max@max-VirtualBox:~/app$ sudo gem uninstall http_accept_language
INFO:  gem "http_accept_language" is not installed

Solution

  • I didn't have to use the gem to implement the feature I wanted.

      def set_i18n_locale
        unless params[:locale]
            params[:locale] = extract_locale_from_accept_language_header
        end
        available = ['en', 'kr']
        if available.include? params[:locale]
            I18n.locale = params[:locale]
        end
      end
    
      def extract_locale_from_accept_language_header
        request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
      end
    
      def default_url_options
        { :locale => I18n.locale }
      end
    

    Official Guide and Agile Development helped a lot.