8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Docker上のRuby on Rails 6をVisual Studio Codeでデバッグするまでの手順

Last updated at Posted at 2021-06-23

必要なもの

Docker Desktop
Visual Studio Code

今回の作業環境は以下になります。

image.png

image.png

image.png

Docker ファイルを作成

Dockerfile
FROM ruby
RUN apt-get update -qq
WORKDIR /app
COPY Gemfile* /app/
RUN bundle install
COPY . /app
EXPOSE 3000 1234 26162
CMD ["rails", "server", "-b", "0.0.0.0"]

Gemfile ファイルを作成

Gemfile
source 'https://rubygems.org'
gem 'rails', '~>6'

Docker 内を Visual Studio Code で開く

.devcontainer/devcontainer.json に下記の行を追加しvscodeを開きなおす

devcontainer.json
	"extensions": [
		"rebornix.ruby",
		"wingrunr21.vscode-ruby"
	],
	"workspaceFolder": "/app",
	"workspaceMount": "source=${localWorkspaceFolder},target=/app,type=bind,consistency=delegated"

バージョン確認

TERMINAL
# ruby -v
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux]
# rails -v
Rails 6.1.4.1

Railsプロジェクト作成

TERMINAL
rails new --api --minimal -S -J -T .

動作確認

TERMINAL
rails s

image.png

ブラウザで http://localhost:3000 を開く

デバッグ用 gem 追加しbundle install

Gemfile
group :development do
  gem 'listen', '~> 3.3'
  gem 'debase', '0.2.5.beta2'
  gem 'ruby-debug-ide', '~> 0.7.2'
end

デバッグ用ファイルを作成

.vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Rails server",
            "type": "Ruby",
            "request": "attach",
            "cwd": "${workspaceRoot}",
            "remoteWorkspaceRoot": "/app",
            "remoteHost": "0.0.0.0",
            "remotePort": "1234"
        }
    ]
}

デバッグ起動

TERMINAL
bundle exec rdebug-ide --host 0.0.0.0 --port 1234 --dispatcher-port 26162 -- bin/rails s -p 3000 -b 0.0.0.0

デバッグタブでデバッグ開始
image.png

テスト用コントローラ作成

app/controllers/todos_controller.rb
class TodosController < ApplicationController
    def index
        todos = ['歯磨き', '掃除']
        render json: todos
    end
end
config/routes.rb
Rails.application.routes.draw do
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  resources :todos
end

ブレークポイント設定

image.png

ブレークポイントで止めて変数を確認

ブラウザで http://localhost:3000/todos を開く

image.png

ステップ実行、再開

image.png

8
7
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?