Sinatra is a minimal web application framework for Ruby that allows developers to quickly create web applications. It provides routing capabilities to map HTTP requests to methods and uses a domain specific language for defining routes. Templates can be used to generate responses and Sinatra supports many template engines like ERB, Haml, and Builder. Overall, Sinatra aims to provide a simple and lightweight way to build web applications in Ruby.
35. 1. HTTP method + URL path
get '/path/' do ... # => '/path/'
get '/path/:dir/:file' do ... # => '/path/hoge/fuga'
get '/path/*.*' do ... # => '/path/hoge.xml'
get %r{/path/[w]+} do ... # => '/path/hoge'
first match
40. 3. Filters
before '/usr/*' do ...
before '/' do ...
get '/usr/*' do ...
get '*' do ...
after '/usr/*' do ...
after do ... # => after '*' do ...
41. 3. Filters
/usr/hoge
before '/usr/*' do ...
before '/' do ...
get '/usr/*' do ...
get '*' do ...
after '/usr/*' do ...
after do ... # => after '*' do ...
42. 3. Filters
/usr/hoge
before '/usr/*' do ... 1
before '/' do ...
get '/usr/*' do ... 2
get '*' do ...
after '/usr/*' do ... 3
after do ... # => after '*' do ...
43. 3. Filters
/usr/hoge /
before '/usr/*' do ... 1
before '/' do ...
get '/usr/*' do ... 2
get '*' do ...
after '/usr/*' do ... 3
after do ... # => after '*' do ...
44. 3. Filters
/usr/hoge /
before '/usr/*' do ... 1
before '/' do ... 1
get '/usr/*' do ... 2
get '*' do ... 2
after '/usr/*' do ... 3
after do ... # => after '*' do ... 3
45. 3. Filters
/usr/hoge / /fuga
before '/usr/*' do ... 1
before '/' do ... 1
get '/usr/*' do ... 2
get '*' do ... 2
after '/usr/*' do ... 3
after do ... # => after '*' do ... 3
46. 3. Filters
/usr/hoge / /fuga
before '/usr/*' do ... 1
before '/' do ... 1
get '/usr/*' do ... 2
get '*' do ... 2 1
after '/usr/*' do ... 3
after do ... # => after '*' do ... 3 2
47. 4. Passing
get '*' do
pass if rand <= 0.2;
# xxx
end
get '*' do
# xxx
end
first match
48. 4. Passing
get '*' do
pass if rand <= 0.2;
# xxx
end
get '*' do
# xxx
end
first match
49. 5. Halt & Error
error 403 do
'Access Forbidden'
end
before '/secret/*' do
halt 403 unless authorized
end
50. 5. Halt & Error
error 403 do
'Access Forbidden'
end
before '/secret/*' do
halt 403 unless authorized
end
51. 5. Halt & Error
error 404 do
'File Not Found'
end
before '/devel/*' do
halt 'xxx'
end
53. URL pattern (:xxx)
get '/path/:dir/:file' do # => '/path/hoge/fuga'
params[:dir] # => "hoge"
params[:file] # => "fuga"
end
54. URL pattern (*)
get '/path/*.*' do # => '/path/hoge/fuga.xml'
params[:splat] # => [ "hoge/fuga", "xml" ]
end
get '/path/*.*' do |path, ext| # => '/path/hoge/fuga.xml'
path # => "hoge/fuga"
ext # => "xml"
end
55. URL regular expression
get %r{/path/([w]+)} do # => '/path/hoge'
params[:capture] # => [ "hoge" ]
end
get %r{/path/([w]+)} do |cap| # => '/path/hoge'
cap # => [ "hoge" ]
end