Rails routes constraint - unicode regex not matching - ruby-on-rails

So I have a route with a constraint that matches paths such as the following:
/jobs-in-London
get ':id' => 'search#show', :constraints => { :id => /jobs-in-[A-Z].*/ }
This works great, but I need to match to locations written in other character sets, such as Japanese. I am happy for the "jobs-in-" to remain in english, since the valid urls are generated from a list of locations uploaded by the user.
This means I would be expecting to match /jobs-in-東京, which would then search in Tokyo once it hit the controller. Geolocation is done later, and works without translation. I just need to get the request to the right controller.
I have tried this:
get ':id' => 'search#show', :constraints => { :id => /jobs-in-\p{L}*/ }
which I constructed using Rubular, and it appears to match correctly as seen here. I am aware this doesn't have the capital letter constraint, but that doesn't matter as some languages don't seem to have true capital letters anyway.
However the routes don't match it, and instead spit it out to the wildcard catch all at the bottom.
Am I falling foul of how Rails implements regex for routes? Does it not support the unicode selectors?
I cannot have this:
get ':id' => 'search#show', :constraints => { :id => /jobs-in-.*/ }
as this matches /jobs-in-$£# which is undesired, I want to constrain it to "letter" characters.

I wanted to match routes like /foo/a and /foo/ä, where that last bit could be non-ASCII letters like "ä".
On Rails 4.2, I had no luck with
get "foo/:letter" => "foos#bar", letter: %r{[[:alpha:]]}
or other variations of the regex that I tried, but this worked fine:
get "foo/:letter" => "foos#bar",
constraints: ->(request) {
# Matching with `letter: some_regex` did not work with åäö.
letter = request.path_parameters[:letter]
letter.match(/\A[[:alpha:]]\z/u)
}

Related

Rails 3 Routing based on regex

I want to redirect all routes that start with the string xyz to some other path.
match /\/xyz\/(.)*/ => redirect{ "whateverurl" }
The match method doesn't seem to work when given a regex, I have googled alot seems like there are options to do with regex but they are for params for example
match 'photos/:id' => 'photos#show', :constraints => { :id => /[A-Z]\d{5}/ }
How can I achieve it ?
How about:
match '/xyz/*foo' => redirect('url')
It's not a regexp, it's called route globbing. More about it here.

Routing more than one action to the same controller and action

I am trying to get something like this working on my Rails app:
match '/:language', :to => 'posts#search_result'
match '/:tag', :to => 'posts#search_result'
match '/:language/:tag', :to => 'posts#search_result'
I am using this search_result action to filter some posts depending of the language and the tag.
The problem is that sometimes :tag will be nil or :language will be nil; so i have these 3 possibilities when calling the action:
<%=link_to "Spanish", {:controller => 'posts', :action => 'search_result', :language => "spanish"} %>
<%= link_to "Spanish", {:controller => 'posts', :action => 'search_result', :language => "spanish", :tag => #tag} %>
<%=link_to "#{tag.name}", {:controller => 'posts', :action => 'search_result', :tag => #tag} %>
And I am expection to have URLs like:
/spanish (for the first case)
/spanish/rails (where rails is a tag, for the second case)
/rails (for the third case)
But right now i am getting the rigth thing for the first and third case, but for the second case i am getting:
/spanish?tag=rails
or again /spanish (depending on if i had selected a tag first or a language first).
I hope i explained myself right. Any idea??. thanks!.
The router cannot tell the difference between a :language and a :tag.
Just because your routes say "language" and "tag" when you are constructing your code in the view.. remember that in the html this has been translated into just plain ole URLs eg /spanish or /rails
the route then has to be figured out from this URL.
Now as I said, the router can't tell that a particular word is a language or a tag... and the plain-ole-URL doesn't have the word "tag" or "language" in it anymore... so your two routes here:
match '/:language', :to => 'posts#search_result'
match '/:tag', :to => 'posts#search_result'
are both the same kind of URL
Just a single token after the slash. Here are some examples that will match that route:
/greek
/spanish
/rails
/urdu
/whatever
They will all match the first route that matches on "a single token after a slash"... which means your router will match all of them to the "language" route and will never ever match the "/:tag" route, because it's already matched on the route above.
he he: it's all greek to the router ;)
Edit:
Hi, this is helping me a lot to understand how routing works.. but still i can't see it clear. I understand what you said, and so basically i understand i should do something like match '/tags/:tag to at least only route to posts#search_result the URLS starting by /tag .. what would be a solution??
yes, "/tags/:tag" would be clear and unambiguous, but if you want it to truly flexible in tag vs language you would be better served by the simple:
match '/posts/search', :to => 'posts#search_result'
which can use any of your link_to examples above to generate eg:
/posts/search?tag=rails
/posts/search?language=spanish
/posts/search?language=spanish&tag=rails
It's also far more clear what is being passed and why.
The description of the third URL is "I'm searching for a set of posts which have language = spanish and tag = rails"
Your URL should reflect the resource (which in this case is a set of posts) everything else is better done as query params.
Instead of defining /:language and /:language/:tag separately, define them together, with /:tag as an optional URI element.
match '/:language(/:tag)', :to => 'posts#search_result'
I believe routes are matched (and URIs generated from them) in the order that the routes are defined. You defined /:lang before you defined /:lang/:tag, so it matched /:lang and made :tag a GET parameter. I suppose you could optimize the ordering of your definitions, but I believe using the above syntax is the preferred method.

ruby on rails - routes.rb - match file extension when multiple periods exist in filename

I have created a route plus controller for doing dynamic css in ruby on rails as per the instructions here:
http://www.misuse.org/science/2006/09/26/dynamic-css-in-ruby-on-rails/
It took some changing to account for a newer version of ruby on rails, but the problem comes in with the routes.rb entry. The original entry was this:
# dynamic CSS (stylesheets)
map.connect 'rcss/:rcssfile',
:controller => 'rcss',
:action => 'rcss'
This did not work with a newer version of RoR, and I found this solution to work:
# dynamic CSS (stylesheets)
map.connect 'rcss/:rcssfile.css',
:controller => 'rcss',
:action => 'rcss'
However, now I was bummed that I couldn't get a catch-all filetype extension handler. The request had to have the .css extension. Playing around with it further I came up with this:
# dynamic CSS (stylesheets)
map.connect 'rcss/:rcssfile.:format',
:controller => 'rcss',
:action => 'rcss'
So this is much better. Now I could potentially request a file that ended in .foobar or whatever and match it with a handler. Not that I would necessarily, but it's more about understanding everything.
So then I tried creating a file that looked something like "foo.net.rcss" . Now it would seem that the first dot messes everything up. "no routes match rcss/foo.net.css". My questions are as follows:
How can I match any filename and any extension regardless of how many dots are in the filename?
Why does the first example not work in later RoR versions?
Why do multiple dots screw up the match?
Thanks in advance for any help.
------- update -------
I am using Rails 3.0.5 . As per some more research I can shorten the syntax to:
match 'rcss/:rcssfile', :to => 'rcss#rcss'
This is the equivalent of the first example that did not seem to work, however using this syntax it works just as expected.
match 'rcss/:rcssfile:.:format', :to => 'rcss#rcss'
This also works just like my previous example #3, however it still has the problem of not matching a file with multiple periods.
It would seem that labeling a standard ":paramater" takes special consideration for the period character. ":parameter" will match a path with up to one period, ":parameter.:extension" will match a path with up to two periods, but the :extension will be only what's between the two periods, etc.
A way around this is to use what is called "Route Globbing", which uses an asterisk instead of a colon:
match 'rcss/*rcssfile', :to => 'rcss#rcss'
The only caveat is that this will match ANYTHING after the asterisk, including subdirectories. As such, you want to make sure that this does not accidentally expose any secure files or accidentally render things unintentionally.
I used this for a general case when you don't know the extension:
get '/uploads/:basename.:extension', to: 'controller#action', basename: /.*(?=\.[\w\d]+$)/
Use a regex to match the filename?
map.connect 'rcss/:rcssfile',
:controller => 'rcss',
:action => 'rcss',
:requirements => {:rcssfile => /.+\.rcss/ }
This would match (anything).rcss - you could adjust the regex for various suffixes.

Rails 3 routing constraints don't seem to be matching the regex properly

I am using Rails 3.0.5 and I have setup a route using a regex constraint. It used to work on Rails 2.3.5, but it's not working in Rails 3. The route looks like this:
get '/:version_id' => 'pastes#show', :constraints => { :version_id => /[\d\w]{40}/ }
It doesn't work at all. However, the following work:
get '/:version_id' => 'pastes#show', :constraints => { :version_id => /.{40}/ }
get '/:version_id' => 'pastes#show', :constraints => { :version_id => /\w{40}/ }
get '/:version_id' => 'pastes#show'
Is there something wrong with the way Rails handles [ ] matching? or am I doing something wrong?
version_id usually looks something like this:
816616001d7ce848944a9e0d71a5a22d3b546943
I don't have a solution as to why one may not work over the other.
However, according to the PickAxe book, \w is actually a superset of \d.
\w [A-Za-z0-9\_] ASCII word character
\d [0-9] ASCII decimal digit character
Therefore, [\d\w]{40} is no different from \w{40}, which works for you.

Rails Routing Conditional with multiple value options

I have a rails route that is based on two conditions, that the domain and subdomain are a specific value. The problem is that there are multiple possible values for subdomain to work, but I can't seem to be able to pass them as an array or hash.
map.with_options(:conditions => {:domain => AppConfig['base_domain'], :subdomain => 'www'..'www3'}) do |signup|
signup.plans '/signup', :controller => 'accounts', :action => 'plans'
...[truncated]...
end
The above example works as accepting www, www1, www2 & www3 as a value for the subdomain. However, that doesn't really solve my needs. I need to be able to accept a value of '' (nothing), 'www' and 'www2' so I tried something to the extend of:
map.with_options(:conditions => {:domain => AppConfig['base_domain'], :subdomain => ['','www','www2']}) do |signup|
That's similar to how you would set it up in ActiveRecord but it doesn't seem to be the same for routes.
Does anybody know now I can specify three values that aren't sequential?
If you can render it as a regular expression, you can use it as a condition. Converting an array to a regular expression is quite easy:
:subdomain => Regexp.new(%w[ www www3 ].collect { |p| Regexp.escape(p) }.join('|'))
Since you're just dealing with a simple pattern anyway, why not express it as this?
:subdomain => /www\d*/
It is important to note that the regular expressions used by routes are not supposed to be anchored using ^ or $ like you usually would. They must match completely to be valid, and partial matches are ignored.

Resources