LoginSignup
3
7

More than 5 years have passed since last update.

Sinatraメモ

Last updated at Posted at 2015-05-16

Sinatraとは

  • Rubyで計量Webアプリケーション
  • DSL(Domain Specific Language)

Sinatraをさっさと使ってみよう

インストール

$ gem install sinatra
...
installed

ディレクトリ構成

※railsのように勝手にファイル生成はされないので、自分でディレクトリ切ってファイルを作成する

/sinatra_app
 ├─ /controller
 ├─ /lib
 ├─ /public
 ├─ /views
 ├─ app.rb
...
ファイル 説明
/controller アプリケーションを配置する
/lib 汎用的なプログラムを配置する
/public 静的ファイル(html, css, 画像)を配置する
/views 動的ファイル(erb)を配置する
app.rb メインアプリケーション

実装する

app.rb
require "sinatra"

get "/hello/:name" do |n|
  "hello #{n}"
end

表示する

sinatraの起動

$ ruby app.rb

実行結果

ブラウザでhttp://localhost:4567/hello/bobにアクセス

/hello/bob
hello bob

これで最低限のWebアプリが完成!

もうちょっと高度に使ってみる

オートリロード

インストール

$ gem install sinatra-contrib
...
installed

有効にする

app.rb
require "sinatra/reloader" # 追加
...

Rubyの書き方あれこれ

パスの書き方あれこれ

主に3つの書き方があるのかな?

app.rb
get "/hello/:name" do |n|
  "hello #{n}"
end
app.rb
get "/hello/*" do |n|
  "hello #{n}"
end
app.rb
get "/hello/:name" do
  "hello #{params[:name]}"
end

実行結果

すべて同じ実行結果になる

/hello/tom
hello tom

URLのパスをオプショナルにする

オプショナルにしたいパスの単語の前後に?をつける

app.rb
get "/konitiwa/:first_name/?:last_name?" do |fn, ln|
  "konitiwa #{fn} #{ln}"
end

実行結果

/konitiwa/maruyama
konitiwa maruyama
/konitiwa/maruyama/hikaru
konitiwa maruyama hikaru
3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7