Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes.rb - Matching case insensitive

Urls are (for an unclear reason, generate different problems/no real advantage) defined case sensitive by w3.

What are my possibilities in routes.rb match case insensitively?

here the matching:

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

Url Example: /europe/library/page4711

calls show action in library controller with { :foo => "europe", :bar => "page4711" }

What I want are 2 things:

  • the param value of :foo needs a .downcase so /Europe should be { :foo => "europe" }
  • library should match case insensitively (ie. /Library, /LIBRARY, /liBRarY all should match)

How do I do this in routes.rb?

Thanks!

like image 859
Calmon Avatar asked Oct 16 '12 14:10

Calmon


2 Answers

Ok, to answer my own question:

There is no good way to do this within Rails routes.rb.

Here what I did:

For the first thing I created a before_filter in my controller:

before_filter :foo_to_lower_case

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

For the second one I created a load balancer rule to get it lowercase to the rails app. Of course you can define a nginx/apache rule as well instead.

Edit: I found another solution for the second part because I disliked the pre-parsing/replacing of every url.

I made "library" to a symbol and wrote a constrained for it which only accept any form of the word "library".

So the line in routes.rb looks like:

match '/:foo/:library/:bar' => 'library#show', :constraints => { :library => /library/i }
like image 132
Calmon Avatar answered Oct 06 '22 04:10

Calmon


Just add this to your Gemfile

gem 'route_downcaser'

restart rails, no configuration needed. the github for this project is at:

https://github.com/carstengehling/route_downcaser

As noted in the gem "Querystring parameters and asset paths are not changed in any way."

like image 34
rdaniels Avatar answered Oct 06 '22 05:10

rdaniels