class Rack::UserLocale
Constants
- VERSION
Attributes
app[R]
body[R]
env[R]
headers[R]
options[R]
status[R]
Public Class Methods
new(app, options = {})
click to toggle source
# File lib/user_locale.rb, line 9 def initialize(app, options = {}) @app = app @options = { accepted_locales: [], cookie_name: "user-locale" }.merge(options) end
Public Instance Methods
call(env)
click to toggle source
# File lib/user_locale.rb, line 17 def call(env) @env = env set_i18n app.call(env) && return unless request.get? @status, @headers, @body = app.call(env) set_response_cookie response.finish end
Private Instance Methods
accepted_locale(locale, other_locale = nil)
click to toggle source
# File lib/user_locale.rb, line 29 def accepted_locale(locale, other_locale = nil) options[:accepted_locales].include?(locale) ? locale : other_locale end
browser_locale()
click to toggle source
# File lib/user_locale.rb, line 33 def browser_locale @browser_locale ||= detect_browser_locale end
check_accepted?()
click to toggle source
# File lib/user_locale.rb, line 37 def check_accepted? @check_accepted ||= options[:accepted_locales].count.positive? end
default_locale()
click to toggle source
# File lib/user_locale.rb, line 45 def default_locale @default_locale ||= I18n.default_locale end
detect_browser_locale()
click to toggle source
# File lib/user_locale.rb, line 49 def detect_browser_locale return if http_accept_languages.nil? if check_accepted? weighted_langs.each do |lang| l = accepted_locale(split_lang(lang.first).to_sym) return l unless l.nil? end end split_lang(weighted_langs.first.first) end
http_accept_languages()
click to toggle source
# File lib/user_locale.rb, line 62 def http_accept_languages @http_accept_languages ||= env["HTTP_ACCEPT_LANGUAGE"] end
request()
click to toggle source
# File lib/user_locale.rb, line 66 def request @request ||= Rack::Request.new(env) end
response()
click to toggle source
# File lib/user_locale.rb, line 70 def response @response ||= Rack::Response.new(body, status, headers) end
set_i18n()
click to toggle source
# File lib/user_locale.rb, line 74 def set_i18n new_locale = check_accepted? ? accepted_locale(user_locale.to_sym, default_locale) : user_locale.to_sym I18n.locale = env["rack.locale"] = new_locale end
split_http_accept_languages()
click to toggle source
# File lib/user_locale.rb, line 85 def split_http_accept_languages @split_http_accept_languages ||= http_accept_languages.split(",").map do |l| l += ";q=1.0" unless l =~ /;q=\d+\.\d+$/ l.split(";q=") end end
split_lang(lang)
click to toggle source
# File lib/user_locale.rb, line 92 def split_lang(lang) return if lang.nil? lang.split("-").first end
user_locale()
click to toggle source
# File lib/user_locale.rb, line 98 def user_locale @user_locale ||= cookie_locale || browser_locale || default_locale end
weighted_langs()
click to toggle source
# File lib/user_locale.rb, line 102 def weighted_langs @weighted_langs ||= split_http_accept_languages.sort { |a, b| b[1] <=> a[1] } end