LoginSignup
7
6

More than 5 years have passed since last update.

Sinatraの導入

Posted at

目的

  • Sinatraでの開発が可能な状態を作る手順を整理

前提

  • Mac High Sierra
    • windowsでやる場合はvagrant上で
  • ruby 2.4.1 (rubyが入っていない場合は、下部参照を確認) (バージョンが変わらない場合は、下部参照を確認)
  • sqlite3 3.19.3

ゴール

  • Sinatoraでの環境構築ができる
  • Hello World がローカルで確認できる
  • 次回
    • アプリを開発する、MVCの基本的な実装ができる
    • Herokuから公開できる

手順

インストール

以下のgemをインストールする
- sinatra
- sinatra-contrib
- activerecord
- sqlite3

gem install sinatra 
gem install sinatra-contrib 
gem install activerecord 
gem install sqlite3

Hollow world表示まで

  • 任意のディレクトリを作成し、rubyファイルを作成
  • 今回は、sinatora_study.rb を作成
sinatora_study.rb
require 'sinatra'
require 'sinatra/reloader'

get '/' do
  'Hello wolrd'
end
  • requireでライブラリが読み込まれる、sinatraでフレームワークが読み込まれ
  • sinatra/reloaderは、WEBRickを再起動しなくても、ソース変更がサーバに適用されるようにする(便利な機能)
  • getリクエストで/(ルート)にアクセスがあった場合、このアクションが実行される
  • 同じパスが設定されていた場合は、最初にマッチしたアクションが実行される

起動オプションを確認

  • -hコマンドで、
ruby sinatora_study.rb -h
$ ruby sinatora_study.rb -h
Usage: sinatora_study [options]
    -p port                          set the port (default is 4567)
    -o addr                          set the host (default is localhost)
    -e env                           set the environment (default is development)
    -s server                        specify rack server/handler (default is thin)
    -q                               turn on quiet mode (default is off)
    -x                               turn on the mutex lock (default is off)
  • vagrantの場合、-oオプションでipを指定する必要がある。ip -a コマンドで確認できる
  • ruby {ファイル名} [オプション] で起動
  • 以下はmacで実行しているため、localhostでOK
ruby sinatora_study.rb
[2018-07-14 14:51:28] INFO  WEBrick 1.3.1
[2018-07-14 14:51:28] INFO  ruby 2.4.1 (2017-03-22) [x86_64-darwin17]
== Sinatra (v2.0.3) has taken the stage on 4567 for development with backup from WEBrick
[2018-07-14 14:51:28] INFO  WEBrick::HTTPServer#start: pid=34071 port=4567

確認

  • ブラウザからアクセスする
  • http://localhost:{port}/
  • ポート番号は、[2018-07-14 14:51:28] INFO WEBrick::HTTPServer#start: pid=34071 port=4567 ここに表示されている

スクリーンショット 2018-07-14 14.55.26.png

  • リクエストが行われると、サーバ側に以下のようなログが出力される
[2018-07-14 14:51:28] INFO  WEBrick::HTTPServer#start: pid=34071 port=4567
::1 - - [14/Jul/2018:14:53:04 +0900] "GET / HTTP/1.1" 200 11 0.0229
::1 - - [14/Jul/2018:14:53:04 JST] "GET / HTTP/1.1" 200 11
- -> /
::1 - - [14/Jul/2018:14:53:04 +0900] "GET /favicon.ico HTTP/1.1" 404 469 0.0008

参照

7
6
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
7
6