gpt4 book ai didi

ruby-on-rails - 使用可选路径前缀创建路由

转载 作者:数据小太阳 更新时间:2023-10-29 06:29:47 26 4
gpt4 key购买 nike

我怎样才能让我的路由识别一个可选的前缀参数,如下所示:

/*lang/controller/id

因为 lang 部分是可选的,如果未在 URL 中指定,则具有默认值:

/en/posts/1   => lang = en
/fr/posts/1 => lang = fr
/posts/1 => lang = en

编辑

理想情况下,我希望通过映射命名空间在多个 Controller 和操作中执行此操作:

map.namespace "*lang" do |lang|
lang.resources :posts
lang.resources :stories
end

最佳答案

好的,我已经设法解决了这个问题:

默认情况下,在 Rails 中没有办法做到这一点(至少现在还没有)。我没有使用 namespace 和默认值,而是需要安装 Sven Fuchs' routing filter .

安装插件后,我将以下文件添加到我的 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'

这基本上填写了一个前后 Hook ,由插件生成,它包装了 rails 路由。

当一个 url 被识别时,在 Rails 开始对它做任何事情之前,around_recognize 方法被调用。这将提取代表语言环境的两个字母代码,并在参数中传递它,如果未指定语言环境,则默认为“en”。

同样,当生成一个 url 时,locale 参数将被推送到左侧的 URL 中。

这给了我以下 url 和映射:

/   => :locale => 'en'
/en => :locale => 'en'
/fr => :locale => 'fr'

所有现有的 url 助手都像以前一样工作,唯一的区别是除非指定语言环境,否则它会被保留:

home_path                  => /
home_path(:locale => 'en') => /
home_path(:locale => 'fr') => /fr

关于ruby-on-rails - 使用可选路径前缀创建路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/212425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com