0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Sinatra】Rubyアプリの作成方法

Last updated at Posted at 2025-04-03

記事概要

フレームワークSinatraによる、Rubyのアプリケーションを作成する方法について、まとめる

言語やフレームワーク

使用技術
フロントエンド HTML
バックエンド Ruby 3.2.0
Sinatra
データベース -
インフラ -
API -
その他 -

前提

  • SinatraをPCにインストールしている
  • PumaをPCにインストールしている

サンプルアプリ(GitHub)

手順

  1. Sinatraの読み込み
    こちらを参照

  2. リクエスト処理を記載
    ルーティングを設定し、リクエスト処理を記述する

    HTTPメソッド '<URL>' do
      # 処理を記述
    end
    
    sinatra.rb
    # PCにインストールしたSinatraをファイルに読み込む
    require 'sinatra'
    
    # ルートパスへアクセスしたときのルーティング
    get '/' do
      
    end
    
  3. レスポンス処理を記載
    ルーティングのdo~endの間にレスポンス処理を記述する

    sinatra.rb
    # PCにインストールしたSinatraをファイルに読み込む
    require 'sinatra'
    
    # ルートパスへアクセスしたときのルーティング
    get '/' do
      # 変数titleに"ONE PIECE"という文字列を代入する
      title = "ONE PIECE"
      
      # 変数titleに代入された値をブラウザに表示する
      "<h1>今週の表紙は、#{title}です</h1>"
    end
    
  4. Webアプリケーションを実行させるため、ターミナル.appで下記コマンドを実行

    # .rbファイルのフォルダへ移動済
    % ruby ファイル名.rb
    
  5. 下記どちらかが表示されると、サーバーが起動している

    • パターン1
      Ignoring debug-1.7.1 because its extensions are not built. Try: gem pristine debug --version 1.7.1
      Ignoring rbs-2.8.2 because its extensions are not built. Try: gem pristine rbs --version 2.8.2
      == Sinatra (v4.1.1) has taken the stage on 4567 for development with backup from Puma
      Puma starting in single mode...
      
    • パターン2
      == Sinatra (v2.0.8.1) has taken the stage on 4567 for development with backup from Puma
      
    • 上記が表示されず、gem install rackupが表示された場合は、再度Rubyを起動する
    • # 下記コマンドの実行
      % gem install rackup
      
      # ynの選択が必要となるので、"y"と入力
      Overwrite the executable? [yN]
      
  6. ブラウザでhttp://localhost:4567にアクセスすると、サーバーに接続できる
    Image from Gyazo

  7. ターミナル.appでcontrol + Cを同時に押すと、サーバーを停止できる

備考

  • SinatraとPumaのインストール方法は、こちらを参照
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?