Ruby on Rails Wednesday, August 31, 2011

Conrad Taylor wrote in post #1019461:
> On Wed, Aug 31, 2011 at 12:01 PM, Conrad Taylor <conradwt@gmail.com>
> wrote:
>
>>> I read that, and I don't see how applying a regex to the id will help.
>>
>> match '/:id' => 'users#show', :constraints => { :id => /[0-9]+/ }
>>
>
> A much better regular expression which matches a value of an :id should
> be
> something like the following:
>
> match '/:id' => 'users#show', :constraints => { :id => /^[1-9]\d*/ }
>

There are still a couple problems with that regex:

1) There is no ending anchor so an id of '10A' would match.
2) You can't use anchors in a regexp for a constraint anyway.


This works for me:


class UserShowConstraint
def matches?(request)
dirname, id = File.split(request.path)
return false unless dirname == '/users'

id =~ /
\A #start of string
[1-9] #not 0
\d* #one or more digits, including 0
\z

No comments:

Post a Comment