【问题标题】:Rails routes.rb - Matching case insensitiveRails routes.rb - 不区分大小写
【发布时间】:2012-10-16 14:04:22
【问题描述】:

W3 定义的 URL 区分大小写(原因不明,会产生不同的问题/没有真正的优势)。

我在 routes.rb 中不区分大小写的可能性是什么?

这里是匹配的:

match '/:foo/library/:bar' => 'library#show'

网址示例:/europe/library/page4711

调用显示库控制器中的操作 { :foo => "europe", :bar => "page4711" }

我想要的是两件事:

  • :foo 的参数值需要一个 .downcase 所以 /Europe 应该是 { :foo => "欧洲" }
  • 库应不区分大小写(即 /Library、/LIBRARY、 /liBRarY 都应该匹配)

如何在 routes.rb 中执行此操作?

谢谢!

【问题讨论】:

标签: ruby-on-rails routes


【解决方案1】:

好的,回答我自己的问题:

在 Rails routes.rb 中没有很好的方法来做到这一点。

我做了什么:

首先,我在控制器中创建了一个 before_filter:

before_filter :foo_to_lower_case

def foo_to_lower_case
  params[:foo] = params[:foo].downcase
end

对于第二个,我创建了一个负载均衡器规则,以将其小写到 rails 应用程序。当然你也可以定义一个 nginx/apache 规则。

编辑:我为第二部分找到了另一个解决方案,因为我不喜欢每个 url 的预解析/替换。

我为一个符号创建了“库”,并为它写了一个约束,它只接受“库”这个词的任何形式。

所以 routes.rb 中的行看起来像:

match '/:foo/:library/:bar' => 'library#show', :constraints => { :library => /library/i }

【讨论】:

  • 优化:params[:foo].downcase!
【解决方案2】:

只需将其添加到您的 Gemfile 中

gem 'route_downcaser'

重启 rails,无需配置。 该项目的 github 位于:

https://github.com/carstengehling/route_downcaser

如 gem 中所述“查询字符串参数和资产路径不会以任何方式更改。”

【讨论】:

  • 很好,但更具体一点会更好
  • 小心,这个 gem 太容易使用了。
【解决方案3】:

要小写路径,您可以设置一个初始化程序来添加一个 Rack 中间件。在这里,我正在检查路径是否以 /posts 开头,而 posts 是否不是较长单词的一部分。有关详细信息,请参阅代码 cmets。

class PathModifier
  def initialize(app)
    @app = app
  end

  def call(env)
    if env['PATH_INFO'] =~ /^\/posts\b/i
      Rails.logger.debug("modifying path")
      %w(PATH_INFO REQUEST_URI REQUEST_PATH ORIGINAL_FULLPATH).each do |header_name|
        # This naively downcases the entire String. You may want to split it and downcase
        # selectively. REQUEST_URI has the full url, so be careful with modifying it.
        env[header_name].downcase!
      end
    end
    @app.call(env)
  end
end
Rails.configuration.middleware.insert(0, PathModifier)

【讨论】:

    猜你喜欢
    • 2023-01-18
    • 2010-10-15
    • 2013-06-23
    • 2015-07-26
    • 2011-05-12
    • 1970-01-01
    • 2012-12-01
    • 2013-03-06
    • 2020-02-18
    相关资源
    最近更新 更多