B87cf29c05d9ce7a26588d6c48e5d988

This is some rails code where I want to take the HTTP_ACCEPT_LANGUAGE header and match it to an array of supported languages. It looks awful here, I know there must be a better way to do this, right?

SUPPORTED_LANGUAGES = [["English", "en"], ["German", "de"]]
# request.env["HTTP_ACCEPT_LANGUAGE"] = "en-us,us;q=0.5"
@languages = request.env["HTTP_ACCEPT_LANGUAGE"].split(';')[0].split(',')
# @languages = ["en-us", "us"]
@languages.each { |lang|
  @match = lang[0..1] if SUPPORTED_LANGUAGES.flatten.include?(lang[0..1])
}
# @match = "en"
if @match
  @language = SUPPORTED_LANGUAGES.find_all { |x| x[1] == @match }[0][0]
else
  @language = SUPPORTED_LANGUAGES[0][0]
end
# @language = "English"

Refactorings

No refactoring yet !

880cbab435f00197613c9cc2065b4f5a

danielharan

October 2, 2007, October 02, 2007 13:54, permalink

No rating. Login to rate!

You can get a list of matching languages in the right order like so:

@matches = @languages.collect {|s| s[0..1]} & SUPPORTED_LANGUAGES.flatten
# ["en"]
8484df61a1434e91cb088f53cc089f18

Adam

August 11, 2008, August 11, 2008 23:43, permalink

No rating. Login to rate!
SUPPORTED_LANGUAGES = { "en" => "English", "de" => "German" }
Mime::Type.parse(request.accept_language).inject(nil) do |result,mime_type|
  result ||= SUPPORTED_LANGUAGES[mime_type.to_s.first(2)]
end
24c5dd45cbb0d72290c63347d88f46fb

Guillaume Noireaux

March 9, 2010, March 09, 2010 16:18, permalink

No rating. Login to rate!
gem install http_accept_language

# usage (from http_accept_language's documentation, exemple two is what was sought):

  class SomeController < ApplicationController
    def some_action

      request.user_preferred_languages
      # => [ 'nl-NL', 'nl-BE', 'nl', 'en-US', 'en' ]

      available = %w{en en-US nl-BE}
      request.preferred_language_from(available)
      # => 'nl-BE'

      request.user_preferred_languages
      # => [ 'en-GB']
      available = %w{en-US}
      request.compatible_language_from(available)
      # => 'en-US'
    end
  end

Your refactoring





Format Copy from initial code

or Cancel