Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>OK, I've managed to sort out this problem:</p> <p>THere is no way of doing this in Rails by default (at least, not yet). Instead of using namespaces and default values, I needed to install <a href="http://github.com/svenfuchs/routing-filter/tree/master" rel="noreferrer">Sven Fuchs' routing filter</a>.</p> <p>Once the plugin is installed, I added the following file to my lib directory:</p> <pre><code>require 'routing_filter/base' module RoutingFilter class Locale &lt; Base # remove the locale from the beginning of the path, pass the path # to the given block and set it to the resulting params hash def around_recognize(path, env, &amp;block) locale = nil path.sub! %r(^/([a-zA-Z]{2})(?=/|$)) do locale = $1; '' end returning yield do |params| params[:locale] = locale || 'en' end end def around_generate(*args, &amp;block) locale = args.extract_options!.delete(:locale) || 'en' returning yield do |result| if locale != 'en' result.sub!(%r(^(http.?://[^/]*)?(.*))){ "#{$1}/#{locale}#{$2}" } end end end end end </code></pre> <p>I added this line to routes.rb:</p> <pre><code>map.filter 'locale' </code></pre> <p>This basically fills out a before and after hook, generated by the plugin, that wraps the rails routing. </p> <p>When a url is recognised, and before Rails gets to do anything with it, the around_recognize method is called. This will extract a two-letter code representing the locale, and pass it through in the params, defaulting to 'en' if no locale is specified.</p> <p>Likewise, when a url is generated, the locale parameter will be pushed into the URL on the left side.</p> <p>This gives me the following urls and mappings:</p> <pre><code>/ =&gt; :locale =&gt; 'en' /en =&gt; :locale =&gt; 'en' /fr =&gt; :locale =&gt; 'fr' </code></pre> <p>All existing url helpers work as before, with the only difference being that unless the locale is specified, it is preserved:</p> <pre><code>home_path =&gt; / home_path(:locale =&gt; 'en') =&gt; / home_path(:locale =&gt; 'fr') =&gt; /fr </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload