ยง2023-02-27
-
In Sinatra, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block:
get '/' do
.. show something ..
end
post '/' do
.. create something ..
end
put '/' do
.. replace something ..
end
patch '/' do
.. modify something ..
end
delete '/' do
.. annihilate something ..
end
options '/' do
.. appease something ..
end
link '/' do
.. affiliate something ..
end
unlink '/' do
.. separate something ..
end
Routes are matched in the order they are defined. The first route that matches the request is invoked.
Routes with trailing slashes are different from the ones without:
get '/foo' do
# Does not match "GET /foo/"
end
Route patterns may include named parameters, accessible via the params hash:
get '/hello/:name' do
# matches "GET /hello/foo" and "GET /hello/bar"
# params['name'] is 'foo' or 'bar'
"Hello #{params['name']}!"
end
- You can also access named parameters via block parameters:
- ?? fifference from the above ???
get '/hello/:name' do |n|
matches "GET /hello/foo" and "GET /hello/bar"
params['name'] is 'foo' or 'bar'
n stores params['name']
"Hello #{n}!" end
- Route patterns may also include splat (or wildcard) parameters, accessible via the params['splat'] array:
get '/say/*/to/*' do
# matches /say/hello/to/world
params['splat'] # => ["hello", "world"]
end
get '/download/*.*' do
# matches /download/path/to/file.xml
params['splat'] # => ["path/to/file", "xml"]
end