⚙️

Dev Containerで作るRuby開発環境(Prettier & Rubocop & RubyLSP対応)

に公開

はじめに

Dev Containerとは、開発環境をコンテナ化することで、開発者が簡単に統一された環境を利用できるようにする仕組みです。詳細は以下の記事をご参照ください。

https://zenn.dev/takayuu/articles/dev-container-80f6900ce9eb8c

本記事では、Dev Containerを使って以下の環境を構築する手順を解説します。

  • Ruby開発環境
    Rubyの実行環境と依存関係管理ツール(Bundler)を設定します。

  • コード品質管理環境
    Prettier、Rubocop、RubyLSPを導入し、コード整形と品質管理を自動化します。

Dev ContainerによるRuby開発環境の構成

準備

必要なツールをインストール

必要な設定項目と確認項目

以下の設定項目を順に確認しながら、進めていきます。

設定項目 確認項目
Dev Containerの起動 コンテナが正常に起動し、VS Code上で作業可能か確認
Node.js・Yarn・Ruby・Bundlerのインストール それぞれが正しくインストールされているか確認
GitHubへのSSH接続設定 コンテナ内からSSHでGitHubに接続できるか確認
Prettierの設定 Prettierでコードが自動整形されるか確認
RuboCopの設定 RuboCopがコードの問題を検出できるか確認

Dev Containerの起動

  1. ルートに以下のファイルとディレクトリを配置し、必要な設定を追加

    /.devcontainer/
      ├── devcontainer.json
      └── Dockerfile
    /.gitignore
    /package.json
    /yarn.lock
    /Gemfile
    /Gemfile.lock
    
    devcontainer.json
    {
      "name": "Ruby",
      "build": {
        "dockerfile": "Dockerfile",
        "context": ".."
      },
      "workspaceFolder": "/workspace",
      "mounts": [
        "source=${localWorkspaceFolder},target=/workspace,type=bind",
        "source=${localWorkspaceFolderBasename}_node_modules,target=/workspace/node_modules,type=volume",
        "source=${localWorkspaceFolderBasename}_bundle,target=/workspace/vendor/bundle,type=volume"
      ],
    }
    
    Dockerfile
    FROM ruby:3.3
    
    WORKDIR /workspace
    
    RUN apt-get update -qq && apt-get install --no-install-recommends -y \
        curl \
        openssh-client \
        && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
        && apt-get install -y nodejs \
        && rm -rf /var/lib/apt/lists/*
    
    RUN npm install -g yarn
    
    COPY ../package.json ../yarn.lock ./
    RUN yarn install
    
    COPY ../Gemfile ../Gemfile.lock ./
    RUN bundle install --path 'vendor/bundle'
    
    COPY . .
    
    .gitignore
    /node_modules
    /vendor
    
    package.json
    {
      "name": "sample",
      "version": "1.0.0",
      "description": "",
      "devDependencies": {},
      "scripts": {},
      "author": "",
      "license": "ISC"
    }
    
    Gemfile
    source 'https://rubygems.org'
    
  2. VS Codeの左下「><」アイコンをクリックし、「Remote-Containers: Reopen in Container」を選択して起動確認

Node.js・Yarn・Ruby・Bundlerの確認

  1. VS Code左下の「><」アイコンをクリックし、「Remote-Containers: Reopen in Container」を選んでコンテナを起動

  2. Node.js・Yarn・Ruby・Bundlerがインストールされていることを確認

    node -v
    v20.0.0
    
    yarn -v
    1.22.19
    
    ruby -v
    ruby 3.3.6
    
    bundle -v
    Bundler version 2.3.27
    

GitHubへのSSH接続設定

  1. コンテナ内のVS CodeからGitHubリポジトリにSSHでアクセスできるよう、Using SSH keys にしたがって設定

  2. コンテナ内のターミナルでssh -T git@github.comを実行して接続を確認

VS Codeの基本設定

  1. devcontainer.jsonにVS Codeの設定を追加

    devcontainer.json
    {
      ...
      "customizations": {
        "vscode": {
          "settings": {
            "editor.tabSize": 2,
            "files.trimTrailingWhitespace": true,
            "files.insertFinalNewline": true,
          }
        }
      }
    }
    
  2. コンテナを再ビルド(Rebuild Container)し、設定を反映

Prettierの設定

  1. yarn add -D prettier でPrettierをインストール

  2. devcontainer.jsonにPrettierの設定とルートに.prettierrc.jsonを新規作成/設定追加

    devcontainer.json
    {
      ...
      "customizations": {
        "vscode": {
          "extensions": [
            "esbenp.prettier-vscode"
          ],
          "settings": {
            ...
            "editor.defaultFormatter": "esbenp.prettier-vscode",
            "editor.formatOnSave": true
          }
        }
      }
    }
    
    .prettierrc.json
    {
      "semi": true,
      "singleQuote": true
    }
    
  3. コンテナを再ビルド(Rebuild Container)し、 Prettierの動作確認

    次のコードを保存すると、自動的に整形されることを確認

    example.js
    const example=()=> {  
      console.log("Hello");  
    }
    

    example.js
    const example = () => {
      console.log('Hello');
    };
    

RuboCopの設定

  1. bundle add rubocop --group "development,test" --require false でRuboCopをインストール

  2. bundle add ruby-lsp --group "development" --require false でRuby LSPをインストール

  3. devcontainer.jsonにRuboCopの設定とルートに.rubocop.ymlを新規作成/設定追加

    devcontainer.json
    {
      ...
      "customizations": {
        "vscode": {
          "extensions": [
            ...
            "Shopify.ruby-extensions-pack"
          ],
          "settings": {
            ...
            "editor.codeActionsOnSave": {
              "source.fixAll": "explicit"
            },
            "[ruby]": {
              "editor.defaultFormatter": "Shopify.ruby-lsp"
            },
            "ruby.lint": {
              "rubocop": true
            }
          }
        }
      }
    }
    
    rubocop.yml
    AllCops:
      TargetRubyVersion: 3.1
      NewCops: enable
      DisplayCopNames: true
    
  4. コンテナを再ビルド(Rebuild Container)し、RuboCopの動作確認
    次のコードを保存すると、VS Code上で「Naming/MethodName: Use snake_case for method names.」というエラーが出力されることを確認

    example.rb
    # frozen_string_literal: true
    
    def testMethod
      puts 'Hello, world!'
    end
    
    

最終フォルダ構成

/.devcontainer/
  ├── devcontainer.json
  └── Dockerfile
/.gitignore
/package.json
/yarn.lock
/Gemfile
/Gemfile.lock
/.prettierrc.json
/rubocop.yml

以上で、Ruby開発環境の構築が完了しました。

サンプルコード

以下のGitHubリポジトリで確認できます。
https://github.com/yuuu-takahashi/template-ruby

Discussion