Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict regex routing

Tags:

ruby

sinatra

I have been experimenting with Sinatra lately and I've been having some "problems" with regex-based routing... For example,

get "/something/" do
  status 400
end

matches /something but neither /something/ nor /somethingelse. However,

get %r{/something/([0-9]{3})} do |number|
  status number
end

matches /something/201 but also /something/201/ and something/201-and-somethingelse. Perhaps I should rewrite the regex to read %r{/something/([0-9]+)$} but it doesn't make sense to me to include the dollar sign since this capture should be strict, right? Or am I missing something?

like image 898
José Fonseca Avatar asked Nov 25 '25 07:11

José Fonseca


1 Answers

Sinata is following the normal regex rules for Ruby. From an IRB session:

pattern = %r{/something/([0-9]{3})}
=> something[0-9]{3}
pattern.match "/something/201"
=> #<MatchData "/something/201" 1:"201">
pattern.match "/something/201/"
=> #<MatchData "/something/201" 1:"201">
pattern.match "something/201-and-somethingelse"
=> nil
pattern.match "/something/201-and-somethingelse"
=> #<MatchData "/something/201" 1:"201">

(this takes into account the typo I pointed out above).

Your other example of get "/something/" do is a string, not a regex, but certain patterns can be included as a convenience e.g. ?. Therefore:

get "/something/" do # will match "/something/" but not "/something"
get "/something" do # will match "/something" but not "/something/"
get "/something/?" do # will match "/something" and "/something/"
like image 59
ian Avatar answered Nov 28 '25 01:11

ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!