Utopia SourceUtopiaLocalization

class Localization

A middleware which attempts to find localized content.

Nested

Definitions

def initialize(app, locales:, default_locale: nil, default_locales: nil, hosts: {}, ignore: [])

Implementation

def initialize(app, locales:, default_locale: nil, default_locales: nil, hosts: {}, ignore: [])
	@app = app
	
	@all_locales = HTTP::Accept::Languages::Locales.new(locales)
	
	# Locales here are represented as an array of strings, e.g. ['en', 'ja', 'cn', 'de'] and are used in order if no locale is specified by the user.
	unless @default_locales = default_locales
		if default_locale
			@default_locales = [default_locale, nil]
		else
			# We append nil, i.e. no localization.
			@default_locales = @all_locales.names + [nil]
		end
	end
	
	@default_locale = default_locale || @default_locales.first
	
	unless @default_locales.include? @default_locale
		@default_locales.unshift(@default_locale)
	end
	
	# Select a localization based on a request host name:
	@hosts = hosts
	
	@ignore = ignore || options[:nonlocalized]
	
	@methods = methods
end

def vary(env, response)

Set the Vary: header on the response to indicate that this response should include the header in the cache key.

Implementation

def vary(env, response)
	headers = response[1].to_a
	
	# This response was based on the Accept-Language header:
	headers << ['Vary', 'Accept-Language']
	
	# Althought this header is generally not supported, we supply it anyway as it is useful for debugging:
	if locale = env[CURRENT_LOCALE_KEY]
		# Set the Content-Location to point to the localized URI as requested:
		headers['Content-Location'] = "/#{locale}" + env[Rack::PATH_INFO]
	end
	
	return response
end