Class: Rack::I18nRoutes

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/i18n_routes.rb

Overview

A middleware component to route translated URLs to their canonical URL.

Examples:

Basic setup with AliasMapping


require 'rack/i18n_routes'

aliases = {
	'articles' => {
		'fra' => 'articles',
		'spa' => ['artículos', 'articulos'],

		:children => {
			'the-victory' => {
				'fra' => 'la-victoire',
				'spa' => 'la-victoria',
			},
			'the-block' => {
				'fra' => 'le-bloc',
				'spa' => 'el-bloque',
			},
		},
	},

	'paintings' => {
		'fra' => 'peintures',
		'spa' => 'pinturas',
	}
}

MAPPING_FN = Rack::I18nRoutes::AliasMapping.new(aliases)

use Rack::I18nRoutes, MAPPING_FN
run MyApp

# /articulos/el-bloque => /articles/the-block
# /articles/le-bloc => /articles/the-block
# /articulos/le-block => /articles/the-block

Constant Summary collapse

ORIG_PATH_INFO_VARIABLE =
'rack.i18n_routes_orig_PATH_INFO'

Instance Method Summary collapse

Constructor Details

#initialize(app, url_mapper) ⇒ I18nRoutes #initialize(app, url_mapping_fn) ⇒ I18nRoutes

Set up an i18n routing table.

Overloads:

  • #initialize(app, url_mapper) ⇒ I18nRoutes

    Uses the #map method of url_mapper to derive the normalized path.

    aliases = { 'articles' => { 'fra' => 'articles', 'spa' => ['artículos', 'articulos'],

        :children => {
            'the-victory' => {
                'fra' => 'la-victoire',
                'spa' => 'la-victoria',
            },
            'the-block' => {
                'fra' => 'le-bloc',
                'spa' => 'el-bloque',
            },
        },
    },
    

    }

    MAPPING = Rack::I18nRoutes::AliasMapping.new(aliases) use Rack::I18nRoutes, MAPPING

    Parameters:

    • app

      the downstream Rack application

    • url_mapper (#map)

      the mapper that will perform the path normalization

    See Also:

    • Rack::I18nRoutes::AliasMapping#initialize
    • Rack::I18nRoutes::AliasMappingUpdater#initialize
  • #initialize(app, url_mapping_fn) ⇒ I18nRoutes

    Uses the passed function to derive the normalized path.

    MAPPING_FN = Proc.new do |orig_path| orig_path.sub(r^/it/, '/italian/') orig_path.sub('/ristorante/', '/restaurant/') orig_path.sub('/ostello/', '/hostell/') end use Rack::I18nRoutes, MAPPING_FN

    Parameters:

    • app

      the downstream Rack application

    • url_mapping_fn (Proc|lambda)

      the function used to perform the path normalization



105
106
107
108
109
# File 'lib/rack/i18n_routes.rb', line 105

def initialize(app, path_lookup)
	@app = app

	@path_lookup = path_lookup
end

Instance Method Details

#call(env) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/rack/i18n_routes.rb', line 111

def call(env)
	path = env['PATH_INFO']
	normalized_path = if @path_lookup.respond_to?(:map)
		@path_lookup.map(path)
	else
		@path_lookup[path]
	end

	env[ORIG_PATH_INFO_VARIABLE] = path
	env['PATH_INFO'] = normalized_path

	return @app.call(env)
end