Module: UsersHelper

Defined in:
app/helpers/users_helper.rb

Overview

Markup generators for the users controller

Instance Method Summary (collapse)

Instance Method Details

- (String) get_user_language

Get the user's preferred language from the Accept-Language header

Examples:

Set the user's default language by the Accept-Language header

user.locale = get_user_language


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/helpers/users_helper.rb', line 48

def get_user_language
  acc_language = request.env['HTTP_ACCEPT_LANGUAGE']
  if acc_language
    lang = acc_language.scan(/^([a-z]{2,3}(-[A-Za-z]{2})?)/).first[0]
    if lang.include? '-'
      # Capitalize the country portion (many browsers send it lowercase)
      lang[-2, 2] = lang[-2, 2].upcase
      lang
    else
      lang
    end
  else
    I18n.default_locale.to_s
  end
end

- (String) options_from_locales(current = I18n.locale)

Create a localized list of languages

This method uses the translated languages and territories lists from the CLDR to create a set of option tags, one per each available locale (similar to options_from_collection in Rails) that can be placed inside a select element. The locale specified in current will be selected.

Examples:

Create a select box for the locale

<select name='locale'><%= options_from_locales(user.locale) %></select>


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'app/helpers/users_helper.rb', line 17

def options_from_locales(current = I18n.locale)
  list = []

  Rails.application.config.i18n.available_locales.each do |loc|
    parts = loc.split('-')
    entry = ''

    if parts.count == 1
      # Just a language, translate
      entry = I18n.t("languages.#{loc}")
    elsif parts.count == 2
      # A language and a territory
      entry = I18n.t("languages.#{parts[0]}")
      entry += ' ('
      entry += I18n.t("territories.#{parts[1]}")
      entry += ')'
    end

    list << [entry, loc]
  end

  list.sort! { |a, b| a[0] <=> b[0] }
  options_for_select(list, current)
end

- (String) options_from_timezones(current = '')

Create a list of all timezones

This function returns a set of option tags for every timezone (similar to options_from_collection in Rails), which can be put inside a select item.

Examples:

Create a select box for the timezone

<select name='timezone'>
  <%= options_from_timezones(user.timezone) %>
</select>


77
78
79
80
81
82
# File 'app/helpers/users_helper.rb', line 77

def options_from_timezones(current = '')
  timezone_options = ActiveSupport::TimeZone.all.map do |tz|
    [tz.to_s, tz.name]
  end
  options_for_select(timezone_options, current)
end