在:id中需要一个可能包含句点的Rails路线,但还要保留可选的:format [英] Need a Rails route with a possible period in the :id, but also retain the optional :format

查看:85
本文介绍了在:id中需要一个可能包含句点的Rails路线,但还要保留可选的:format的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条Rails路线,将股票报价符号作为:id

I have a Rails route that takes stock ticker symbols as the :id


  • feeds / AMZN 将返回亚马逊的页面

  • feeds / AMZN.csv 将返回相同数据的CSV表示形式。

  • feeds/AMZN will return a page for Amazon
  • feeds/AMZN.csv will return a CSV representation of the same data.

但是我还需要容纳VIA.B(Viacom)之类的股票,以便这两种路线都能起作用:

But I also need to accomodate stocks like VIA.B (Viacom) so that both of these routes work:

feeds/VIA.B (html)
feeds/VIA.B.csv (csv)

这可能吗?我该如何设置路由?

Is this possible? How would I set the routing up?

推荐答案

我最近在修补RubyGems API时遇到了这个问题(尝试访问<$使用API​​( /api/v1/gems/flickr.rb.json )的c $ c> flickr.rb 不起作用)。

I ran into this while patching the RubyGems API recently (trying to access the flickr.rb using the API (/api/v1/gems/flickr.rb.json) was not working).

技巧是为路由提供一个正则表达式以处理:id 参数,然后指定有效的:format 。请记住,:id regexp必须是惰性(必须以问号结尾),否则它将占用 .csv 并假定它是id的一部分。以下示例允许ID,JSON,CSV,XML和YAML格式带有句点:

The trick was to supply the route with a regexp to handle the :id parameter, and then specify valid :format. Keep in mind that the :id regexp needs to be "lazy" (must end with a question mark), otherwise it will eat the .csv and assume that it's part of the id. The following example would allow JSON, CSV, XML, and YAML formats for an id with a period in it:

resources :feeds, :id => /[A-Za-z0-9\.]+?/, :format => /json|csv|xml|yaml/

这篇关于在:id中需要一个可能包含句点的Rails路线,但还要保留可选的:format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆