Strict regex routing

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

get "/something/" do
  status 400
end

      

matches /something

, but neither /something/

, nor /somethingelse

. Nevertheless,

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

      

matches /something/201

, but also /something/201/

, and something/201-and-somethingelse

. Maybe I should rewrite the regex to read it %r{/something/([0-9]+)$}

, but it doesn't make sense for me to include the dollar sign since that capture has to be strict, right? Or am I missing something?

+3


source to share


1 answer


Sinata follows the usual Ruby regex rules. 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 accounts for the typo described above).



Another example get "/something/" do

is a string, not a regex, but some patterns can be included as a convenience, for example. ?

... 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/"

      

+2


source







All Articles