Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a Rails route with a possible period in the :id, but also retain the optional :format

Tags:

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

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

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?

like image 842
dan Avatar asked Jul 16 '11 19:07

dan


People also ask

What is RESTful route in Rails?

In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.

What does rake routes do?

rake routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.

How do you define a route in Ruby?

We have to define the routes for those actions which are defined as methods in the BookController class. Open routes. rb file in library/config/ directory and edit it with the following content. The routes.


1 Answers

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).

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/ 
like image 116
Dylan Markow Avatar answered Sep 18 '22 13:09

Dylan Markow