VSCodeでRailsをデバッグする【Rails + vscode-rdbg(debug.gem)】

この記事では、Ruby 3.1で標準ライブラリとなったdebug.gemを使って、VSCode上でRailsアプリのデバッグを行う方法を紹介します。 1. 設定方法 Railsアプリのデバッグを行うために必要な設定を行います。 1-1. debug.gemのインストール ※ Rails 7以降ではデフォルトでdebug.gemが使われるため以下の設定は不要 Gemfileに以下を記述します。 group :development, :test do # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem gem "debug", platforms: %i[ mri mingw x64_mingw ] end bundle installを実行してdebug.gemをインストールします。 1-2. vscode-rdbgのインストール VSCodeの拡張機能「VSCode rdbg Ruby Debugger」を追加します。 VSCode rdbg Ruby Debugger - Visual Studio Marketplace 1-3. launch.jsonファイルの作成 VSCodeのアクティビティバーから「実行とデバッグ(Run and Debug)」を選択し、「launch.jsonファイルを作成します(create a launch.json file)」を選択します。 次に、「デバッガーの選択(Select debugger)」で「Ruby(rdbg)」を選択します。 するとプロジェクトのルートフォルダに.vscode/launch.jsonが作成されます。 作成された.vscode/launch.jsonを以下のように編集してください。 { "version": "0.2.0", "configurations": [ { "type": "rdbg", "name": "Debug Rails", "request": "launch", "cwd": "${workspaceRoot}", "script": "bin/rails server", "args": [], "askParameters": false, "useBundler": true, }, ] } 以上で設定は終了です。 ...

9月 17, 2022

【Git】グローバルなgitignoreの設定方法

この記事では、グローバルなgitignoreの設定方法を紹介します。 グローバルなgitignoreファイル(~/.config/git/ignore)を作成し、全てのリポジトリでGitの追跡対象外とするファイルを定義します。 1. gitignoreとは 意図的に未追跡のファイルを指定して、それらをGitが追跡しないようにするためのもの すでに Git に追跡されているファイルは影響を受けない 現在追跡しているファイルの追跡を止めるには、git rm --cached を使う 2. gitignoreの使い分け .gitignore:特定のリポジトリで全ての人が無視したいファイル $GIT_DIR/info/exclude:特定のリポジトリで自分だけが無視したいファイル $XDG_CONFIG_HOME/git/ignore:全てのリポジトリで自分だけが無視したいファイル 3. グローバルなgitignoreの設定 グローバルなgitignoreの設定には$XDG_CONFIG_HOME/git/ignoreを使用します。 3-1. $XDG_CONFIG_HOME/git/ignoreとは core.excludesfileのデフォルト値 $XDG_CONFIG_HOMEが未設定の場合、代わりに$HOME/.config/git/ignoreが使用される つまり $ git config --global core.excludesfile ~/.gitignore_globalして~/.gitignore_globalを作成する必要はなく、代わりに~/.config/git/ignoreを作成すればok。 ※~/.config/git/ignoreを使用する場合、core.excludesfileの設定の削除が必要 3-2. 設定方法 ~/.config/git/ignoreを作成し、無視したいファイルを追加するだけです。 gitignoreテンプレート:github/gitignore gitignore作成:gitignore.io 【参考】 Git - gitignore Documentation ファイルを無視する - GitHub ドキュメント gitignore を正しく理解したい - うさぎ小屋 ~/.gitignore_global を指定するのをやめ、デフォルトの置き場に置こう 「$HOME/git/ignore」と 「$GIT_DIR/info/exclude」と「.gitignore」の使い分け - セットプチフォッカ Git - git-rm Documentation XDG Base Directory - ArchWiki 最近目にする$HOME/.configというディレクトリ - 理系学生日記 SourceTree が Git のグローバルな無視リストを書き換えて困った話 - てっく煮ブログ .gitignorがないのにファイルがコミットできないときの対処方法

9月 16, 2022

【Rails】kaminariでページング処理を実装する

この記事では、kaminari gemを使ってページング処理(ページネーション)を実装する方法を紹介します。 1. 実行環境 macOS:12.5.1 Ruby:3.1.2 Rails:6.1.7 kaminari:1.2.2 2. 手順 2-1. kaminari gemのインストール Gemfileに以下を追記します。 gem 'kaminari' 以下のコマンドを実行してkaminari gemをインストールします。 bundle install 2-2. ページネーションを実装 コントローラーに以下を追記します。 def index @books = Book.order(:id).page(params[:page]) end デフォルトで25件/ページ Book.page(params[:page])だと並び順が変わることがあるため、必ずorderをつける Active Record クエリインターフェイス - 4 並び順 order - ActiveRecord::QueryMethods ビューファイルに以下を追記します。 <%= paginate @books %> 以上でページネーションの実装は完了です。 2-3. 日本語化 kaminariが表示する"First"や"Last"のような表示を日本語化します。 config/locales/ja.ymlに以下を追記します。 ja: views: pagination: first: '最初' last: '最後' previous: '前' next: '次' truncate: '...' I18n and Labels - GitHub - amatsuda/kaminari 【参考】 GitHub - amatsuda/kaminari kaminari徹底入門 #Ruby - Qiita 【Rails】 kaminariの使い方を理解してページネーションを実装しよう | Pikawaka

9月 16, 2022

【Rails】i18nで日本語化する方法

この記事では、Railsに同梱されているi18n gemを使ってアプリケーションを多言語化する方法を紹介します。 1. 実行環境 macOS:12.5.1 Ruby:3.1.2 Rails:6.1.7 i18n:1.12.0 2. 手順 2-1. i18nモジュールの設定 使用する言語のリストとデフォルトで使用する言語を設定します。 config/initializers/locale.rbに以下を追記します。 # 英語と日本語の利用を許可する I18n.available_locales = [:en, :ja] # デフォルトの言語を日本語にする I18n.default_locale = :ja 2-2. ロケールファイルのダウンロード 使用する言語のデフォルトのロケールファイルをsvenfuchs/rails-i18nからダウンロードします。 日本語 $ curl -s https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml -o config/locales/ja.yml 英語 $ curl -s https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/en.yml -o config/locales/en.yml 上記のコマンドによりconfig/locales/ja.ymlとconfig/locales/en.ymlが作成されます。 以降はこれらのファイルに翻訳を追加していきます。 2-3. Active Recordモデルで翻訳を行なう config/locales/ja.ymlに以下を追記します。 ja: activerecord: models: book: 本 attributes: book: title: タイトル memo: メモ model_name.humanとhuman_attribute_nameを使ってモデル名とカラム名の訳語を表示します。 Book.model_name.human #=> 本 Book.human_attribute_name(:title) #=> タイトル Book.human_attribute_name(:memo) #=> メモ Rails 国際化(i18n)API - 4.7.2 Active Modelのメソッド config/locales/en.ymlに英訳を追加します。 en: activerecord: models: book: Book attributes: book: title: Title memo: Memo 2-4. その他の翻訳 config/locales/ja.ymlに以下を追記します。 ...

9月 15, 2022

【Git】コミット済みファイルを管理対象から除外する方法

Gitは一度ファイルを追跡すると、.gitignoreに追加しても追跡は継続されます。 .gitignoreに追加する前にコミットしてしまった。 リモートリポジトリにすでに追跡されているファイルの追跡をやめたい。 このような既にGitの管理対象になっているファイルの追跡を止めるには以下のコマンドを実行します。 ファイルの場合 git rm --cached <ファイル> ディレクトリの場合 git rm -r --cached <ディレクトリ> 【参考】 Git - git-rm Documentation How do I make Git forget about a file that was tracked, but is now in .gitignore? - Stack Overflow Git: Stop Tracking File After Adding to .gitignore How to Stop Git Tracking a File | Alpha Efficiency.™ gitの管理対象から特定のファイル、ディレクトリを削除する #Git - Qiita

9月 14, 2022

【iTerm2】現在のディレクトリのまま新規タブを開く

iTerm2のデフォルトでは、ホームディレクトリで新規タブが開かれます。 これを、元のタブと同じディレクトリで新規タブを開くように設定します。 1. 実行環境 iTerm2:3.4.16 2. 設定方法 Preference > Profile > Working Directory > Reuse previous session’s directory 以上で設定は終了です。 2-1. 追加設定 Advanced Configuration > Edit… 新規タブのほかに、新規ウィンドウとパネル分割時のディレクトリ設定が可能

9月 12, 2022

【Ruby】Sinatraでメモアプリを作る(DB編)

この記事では、RubyのWebアプリケーションフレームワークであるSinatraを使って、シンプルなメモアプリを作成します。 データ保存先のDBにはPostgreSQLを使用します。 今回は、以下の記事で作成したメモアプリのデータ保存先をPostgreSQLに変更します。 【Ruby】Sinatraでメモアプリを作る(JSONファイル編) | あまブログ PostgreSQLのインストール方法は以下を参照ください。 【macOS】PostgreSQLの基本操作 | あまブログ 1. 実行環境 macOS:12.5 Ruby:3.1.0 Bundler:2.3.12 PostgreSQL:14.3 sinatra:2.2.2 webrick:1.7.0 sinatra-contrib:2.2.2 pg:1.4.3 2. 手順 2-1. pgのインストール RubyからPostgreSQLを使うために必要なgem、pgをインストールします。 Gemfileに以下を追加します。 + gem "pg" gem "sinatra" 以下のコマンドを実行してgemをインストールします。 $ bundle install 2-2. DB接続とテーブル定義 memo.rbでpgを使えるようにします。 - require 'json' + require 'pg' memo.rbの以下の部分を削除します。 FILE_PATH = 'public/memos.json' def get_memos(file_path) File.open(file_path) { |f| JSON.parse(f.read) } end def set_memos(file_path, memos) File.open(file_path, 'w') { |f| JSON.dump(memos, f) } end memo.rbに以下を追加します。 def conn @conn ||= PG.connect(dbname: 'postgres') end configure do result = conn.exec("SELECT * FROM information_schema.tables WHERE table_name = 'memos'") conn.exec('CREATE TABLE memos (id serial, title varchar(255), content text)') if result.values.empty? end PG.connectでDBに接続し、インスタンス変数@connに接続情報をキャッシュ configurationにはアプリ起動時に一度だけ行う処理を記述 PostgreSQLのシステムテーブルtablesからmemosテーブルの存在を確認 if result.values.empty?でmemosテーブルがなければテーブルを作成 2-3. メモ一覧の表示 memo.rbに以下を追加します。 ...

8月 19, 2022

【Ruby3.1】wcコマンドを作る

この記事では、RubyでLinuxのwcコマンドを実装する方法を解説します。 gemを使わずにRubyの標準ライブラリのみで実装します。 1. 実行環境 macOS:12.5 Ruby:3.1.0 2. 作成するwcコマンドの要件 オプションなし 標準入力とファイルの入力を受け取る -cオプション -lオプション -wオプション 単語の区切り文字は半角スペース、タブ、改行のみに対応 以下の機能は実装の対象外とします。 ノーブレークスペースを含むマルチバイト文字の対応 3. wcコマンドの仕様 macOS標準のwcコマンドの仕様は以下の通りです。(ソースコードはこちら) (今回の要件に必要な箇所のみ) 引数なし 標準入力を受け取る Ctrl + D(EOF)を受け取るまで入力を受け付ける 引数にファイルを指定 ファイルを受け取る 複数ファイルを指定した場合、出力の最終行に各ファイルの合計を表示 <合計の行数> <合計の単語数> <合計のバイト数> total オプションなし <行数> <単語数> <バイト数> <ファイル名>の順で表示 -cオプション バイト数を表示する -lオプション 行数を表示する(改行コードの数) -wオプション 単語数を表示する 半角スペース、タブ、改行で区切られた文字列の数(全角スペースはmacOS標準のwcコマンドも非対応) 4. ソースコード ver1:自作→レビュー反映 ver2:ver1→他の人のコードを反映 4-1. ver1 #!/usr/bin/env ruby # frozen_string_literal: true require 'optparse' def exec options = parse_options options = { c: true, l: true, w: true } if options.empty? paths = ARGV paths.empty? ? display_word_count_from_stdin(options) : display_word_count_from_files(paths, options) end def parse_options opt = OptionParser.new options = {} opt.on('-c') opt.on('-l') opt.on('-w') opt.parse!(ARGV, into: options) options end def display_word_count_from_stdin(options) lines = $stdin.readlines word_count_map = build_word_count_map(lines) display_word_count(word_count_map, options) end def build_word_count_map(lines, path = '') { number_of_lines: count_line(lines), number_of_words: count_word(lines), bytesize: count_bytesize(lines), path: path } end def count_line(lines) lines.size end def count_word(lines) lines.sum { |line| line.split(/[ \t\n]+/).size } end def count_bytesize(lines) lines.sum(&:bytesize) end def display_word_count(word_count_map, options) word_counts = [] word_counts << format_word_count(word_count_map[:number_of_lines]) if options[:l] word_counts << format_word_count(word_count_map[:number_of_words]) if options[:w] word_counts << format_word_count(word_count_map[:bytesize]) if options[:c] word_counts << " #{word_count_map[:path]}" unless word_count_map[:path].empty? puts word_counts.join end def format_word_count(word_count) word_count.to_s.rjust(8) end def display_word_count_from_files(paths, options) word_count_maps = build_word_count_maps(paths) word_count_maps.map { |word_count_map| display_word_count(word_count_map, options) } display_total_word_count(word_count_maps, options) if paths.size >= 2 end def build_word_count_maps(paths) paths.map do |path| lines = File.readlines(path) build_word_count_map(lines, path) end end def display_total_word_count(word_count_maps, options) total_word_count_map = build_total_word_count_map(word_count_maps) display_word_count(total_word_count_map, options) end def build_total_word_count_map(word_count_maps) { number_of_lines: word_count_maps.sum { |word_count_map| word_count_map[:number_of_lines] }, number_of_words: word_count_maps.sum { |word_count_map| word_count_map[:number_of_words] }, bytesize: word_count_maps.sum { |word_count_map| word_count_map[:bytesize] }, path: 'total' } end exec 4-2. ver2 #!/usr/bin/env ruby # frozen_string_literal: true require 'optparse' def exec options = parse_options options = { c: true, l: true, w: true } if options.empty? paths = ARGV counts = build_counts(paths: paths) counts.map { |count| display_count(count: count, options: options) } display_total_count(counts: counts, options: options) if paths.size >= 2 end def parse_options opt = OptionParser.new options = {} opt.on('-c') opt.on('-l') opt.on('-w') opt.parse!(ARGV, into: options) options end def build_counts(paths:) if paths.empty? [build_count(text: $stdin.read)] else paths.map do |path| build_count(text: File.read(path), path: path) end end end def build_count(text:, path: '') { line_count: text.count("\n"), word_count: text.split(/\s+/).size, bytesize: text.bytesize, path: path } end def display_count(count:, options:) formatted_counts = [] formatted_counts << format_count(count: count[:line_count]) if options[:l] formatted_counts << format_count(count: count[:word_count]) if options[:w] formatted_counts << format_count(count: count[:bytesize]) if options[:c] formatted_counts << " #{count[:path]}" unless count[:path].empty? puts formatted_counts.join end def format_count(count:) count.to_s.rjust(8) end def display_total_count(counts:, options:) total_count = build_total_count(counts: counts) display_count(count: total_count, options: options) end def build_total_count(counts:) { line_count: counts.sum { |count| count[:line_count] }, word_count: counts.sum { |count| count[:word_count] }, bytesize: counts.sum { |count| count[:bytesize] }, path: 'total' } end exec 【参考】 ...

8月 18, 2022

【Ruby】rbenvのよく使うコマンド一覧

この記事ではrbenvのよく使うコマンドを紹介していきます。 1. バージョン確認 1-1. 現在使用中のRubyのバージョンを表示 $ rbenv version 1-2. インストール済みのRubyのバージョンを表示 $ rbenv versions ~/.rbenv/versionsのRubyのバージョンを表示 2. インストール 2-1. インストール可能なRubyの最新安定版のバージョンを表示 $ rbenv install -l/--list 2-2. インストール可能なRubyの全バージョンを表示 $ rbenv install -L/--list-all 2-3. Rubyのインストール $ rbenv install <version> ~/.rbenv/versionsにインストールされる 2-4. Rubyのアンインストール $ rbenv uninstall <version> 3. バージョン指定 バージョンの優先順位 環境変数: RBENV_VERSION ローカル :rbenv local <version> グローバル:rbenv global <version> 3-1. デフォルトで使用するRubyのバージョンを指定 $ rbenv global <version> ~/.rbenv/versionが作成され、グローバルに設定したRubyのバージョンが書き込まれる 3-2. カレントディレクトリで使用するRubyのバージョンを指定 $ rbenv local <version> カレントディレクトリに.ruby-versionが作成され、ローカルに設定したRubyのバージョンが書き込まれる rbenv local --unsetで解除 3-3. シェル単位で使用するRubyのバージョンを指定 $ rbenv shell <version> 環境変数$RBENV_VERSIONに指定したRubyのバージョンがセットされる rbenv shell --unsetで解除 4. その他 4-1. rbenvのバージョンを表示 $ rbenv -v 4-2. rbenvとruby-buildのアップグレード $ brew upgrade rbenv ruby-build 上記はHomebrewのコマンド rbenv install -lでRubyの最新安定版のバージョンが表示されない時はrbenvとruby-buildの更新が必要かも 4-3. rbenvのヘルプを表示 $ rbenv -h 4-4. rbenvのコマンド詳細情報を表示 $ rbenv help <command> 【参考】 ...

8月 16, 2022

【Mac】VSCodeのショートカットキーまとめ

この記事ではMacユーザー向けに、Visual Studio Codeのキーボードショートカットの中から特に使用頻度の高いものを紹介していきます。 1. 一般 操作 ショートカット コマンドパレットを開く shift + ⌘ + P クイックオープン ⌘ + P 新規ウィンドウを開く shift + ⌘ + N ウィンドウを閉じる ⌘ + W ユーザー設定を開く ⌘ + , キーボードショートカットを開く ⌘ + K→⌘ + S 2. 基本的な編集 操作 ショートカット 行を下に移動/上に移動 option + ↓ / option + ↑ 行の下にコピー/上にコピー shift + option + ↓ / shift + option + ↑ 行の削除 shift + ⌘ + K 行を下に挿入/上に挿入 ⌘ + Enter / shift + ⌘ + Enter 一致する括弧にジャンプ shift + ⌘ + \ 行のインデント/アウトデント ⌘ + ] / ⌘ + [ コードを折りたたむ/展開する option + ⌘ + [ / option + ⌘ + ] 行コメントの切り替え ⌘ + / 補完機能をトリガー control + space ⌘ + I 3. マルチカーソルと選択 操作 ショートカット カーソルの挿入 option + クリック カーソルを下へ挿入/上へ挿入 option + ⌘ + ↓ / option + ⌘ + ↑ 現在の行を選択 ⌘ + L 選択中の文字列と一致する文字列を全て選択 shift + ⌘ + L 矩形選択 shift + option + マウスドラッグ shift + option + ⌘ + ↑ / ↓ / ← / → 4. 検索と置換 操作 ショートカット 検索 ⌘ + F 置換 option + ⌘ + F 検索結果の次に移動/前に移動 ⌘ + G / shift + ⌘ + G Enter / shift + Enter マッチした文字列を全て選択 option + Enter 5. ナビゲーション 操作 ショートカット 指定行へ移動 control + G 問題パネルを開く shift + ⌘ + M パネルの表示/非表示切り替え ⌘ + J 6. エディタの管理 操作 ショートカット エディタを閉じる ⌘ + W フォルダを閉じる ⌘ + K → F エディタを垂直分割 ⌘ + \ 7. ファイル管理 操作 ショートカット 新規ファイル ⌘ + N ファイルを開く ⌘ + O 保存 ⌘ + S 閉じたエディタを開く shift + ⌘ + T アクティブなファイルを新しいウィンドウに表示する ⌘ + K → O 最近開いた項目 control + R 8. 表示 操作 ショートカット エディタレイアウトの切り替え(水平/垂直) option + ⌘ + 0 サイドバーの表示/非表示の切り替え ⌘ + B 出力パネルの表示 shift + ⌘ + U Markdownプレビューをサイドに表示 ⌘ + K → V Markdownプレビューを新規ファイルとして表示 shift + ⌘ + V ターミナルを表示する control + ` 新しいターミナルを作成する control + shift + ` 9. その他 9-1. ユーザが作成したショートカットキーのみを表示する方法 キーボードショートカットエディターの検索欄に@source:userを入力する ...

8月 12, 2022