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?
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/"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With