好的,我已经设法解决了这个问题:
默认情况下,在 Rails 中没有办法做到这一点(至少目前还没有)。我需要安装Sven Fuchs 的路由过滤器,而不是使用命名空间和默认值。
安装插件后,我将以下文件添加到我的 lib 目录:
require 'routing_filter/base'
module RoutingFilter
class Locale < 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, &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, &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
我将此行添加到 routes.rb:
map.filter 'locale'
这基本上填写了一个由插件生成的前后钩子,它包装了rails路由。
当一个 url 被识别时,在 Rails 对其进行任何操作之前,将调用 around_recognize 方法。这将提取表示区域设置的两个字母代码,并将其传递到参数中,如果未指定区域设置,则默认为“en”。
同样,当生成 url 时,locale 参数将被推送到左侧的 URL 中。
这给了我以下网址和映射:
/ => :locale => 'en'
/en => :locale => 'en'
/fr => :locale => 'fr'
所有现有的 url 助手都像以前一样工作,唯一的区别是除非指定了语言环境,否则它会被保留:
home_path => /
home_path(:locale => 'en') => /
home_path(:locale => 'fr') => /fr