2. 自己紹介
describe Sonots do
its(:company) { should == :DeNA }
it_should_behave_like “DeNA employee”
end
shared_examples_for “DeNA employee” do
it { should write(:perl) } #=> fail
end
9. 基礎 ∼ クラシックスタイル
require 'sinatra'
get '/hello' do
'Hello World!'
end
get '/hello/:name' do
"Hello #{params[:name]}!"
end
$ ruby my_app.rb Gemfile
Gemfile.lock
my_app.rb
起動 ディレクトリ構造
my_app.rb
10. モジュラースタイル
require 'sinatra/base'
class MyApp < Siantra::Base
get '/hello' do
'Hello World!'
end
get '/hello/:name' do
"Hello #{params[:name]}!"
end
end
$ rackup
Gemfile
Gemfile.lock
config.ru
my_app.rb
起動 ディレクトリ構造
# config.ru
require './my_app'
run MyApp
12. 1. Sinatra.register を使う
# my_app.rb
require 'sinatra/base'
require_relative
'posts_controller'
class MyApp < Sinatra::Base
register PostsController
get '/hello' do
'Hello World!'
end
get '/hello/:name' do
"Hello #{params[:name]}!"
end
end Gemfile
Gemfile.lock
config.ru
my_app.rb
posts_controller.rb
ディレクトリ
# posts_controller.rb
module PostsController
def self.registered(app)
app.get '/posts' do
end
app.get '/posts/:id' do
"Post #{params[:id]}"
end
end
end
14. 2. use (Rack Middleware)
# my_app.rb
class MyApp < Sinatra::Base
get '/hello' do
'Hello World!'
end
get '/hello/:name' do
"Hello #{params[:name]}!"
end
end
Gemfile
Gemfile.lock
config.ru
my_app.rb
posts_controller.rb
ディレクトリ
# posts_controller.rb
class PostsController <
Sinatra::Base
get '/posts' do
end
get '/posts/:id' do
"Post #{params[:id]}"
end
end
# config.ru
require 'sinatra/base'
require './my_app'
require './posts_controller'
use PostsController
run MyApp
16. 本命: URLMap を使う
class HelloController <
Sinatra::Base
get '/hello' do
'Hello World!'
end
get '/hello/:name' do
"Hello #{params[:name]}!"
end
end
Gemfile
Gemfile.lock
config.ru
hello_controller.rb
posts_controller.rb
ディレクトリ
class PostsController <
Sinatra::Base
get '/' do
end
get '/:id' do
"Post #{params[:id]}"
end
end
require 'sinatra/base'
require './hello_controller'
require './posts_controller'
ROUTES = {
'/' => HelloController,
'/posts' => PostsController,
}
run Rack::URLMap.new(ROUTES)
config.ru
18. View ∼ Sinatraにあるよ
class HelloController < Sinatra::Base
set :views, File.expand_path('../views', File.dirname(__FILE__))
get '/hello' do
'Hello World!'
end
get '/hello/:name' do
@name = params[:name]
erb :hello
end
end
Gemfile
Gemfile.lock
config.ru
controllers/
views/
ディレクトリ
<html>
<b>Hello <%= @name %>!</b>
</html>
views/hello.erb