Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rails の CLI ツールの書き方/writing-rails-cli-tool

Rails の CLI ツールの書き方/writing-rails-cli-tool

Avatar for Masatoshi Moritsuka

Masatoshi Moritsuka

August 16, 2025
Tweet

More Decks by Masatoshi Moritsuka

Other Decks in Technology

Transcript

  1. 自己紹介 森塚 真年 GitHub: @sanfrecce-osaka Twitter(X) ・Qiita: @sanfrecce_osaka 趣味: コミュニティ・勉強会

    Machida.rb Hirakata.rb 株式会社Leaner Technologies Ruby3.4/Rails8.0 Next.js 14.2
  2. rake タスク namespace :build do # :test が事前タスク # [:version]

    が引数 # :package がタスク名 task :package, [:version] => :test do |t, args| # ... end end $ rake build:package[1.2.3]
  3. 👍 デフォルトで使える 👍 Rails ガイドにものっている cf. 👍 多くの利用実績 cf. 😭

    引数が扱いづらい 😭 DSL が難しい カスタムRake タスク Data Migration on Rails
  4. rake タスクで拡張した rails stats # lib/tasks/custom_stats.rake task stas: :environment do

    STATS_DIRECTORIES.insert( 13, %w[Services app/services], %w[Libs app/libs] ) end
  5. thor タスク class Build < Thor desc 'package [version]', 'Build

    the specified version of th method_option :dry_run, type: :boolean, default: false, desc: 'dry run def package(version) invoke :test # ... end def test # ... end end $ bundle exec thor build:package --dry-run 1.2.3 Thor がRails に入っている話 - TechRacho rails/thor Wiki
  6. $ bundle exec thor list build ----- thor build:package [version]

    # Build the specified version of $ bundle exec thor help build:package Usage: thor build:package [version] Options: [--dry-run], [--no-dry-run], [--skip-dry-run] # dry run mode # Default: fal Build the specified version of the package.
  7. rails コマンド Rails::Command::Base を継承する Rails::Command::Base は Thor を継承している require 'rails/command'

    module Tasks class Build < Rails::Command::Base namespace :build desc 'package [version]', 'Build the specified version of method_option :dry_run, type: :boolean, default: false, desc: 'dry r def package(version) invoke :test # ... end def test
  8. 👍 thor と同じ使い心地 👍 rails コマンドで統一できる 👍 model を扱う際に require

    が不要 🤔 Rails ガイドには記載がない API Doc はあるので private API ということはな さそう?
  9. $ bin/rails -h # 省略 All commands can be run

    with -h (or --help) for more informati In addition to those commands, there are: # 省略 build:package Build the specified version of $ bin/rails build:package -h Usage: bin/rails build:package [version] Options: [--dry-run], [--no-dry-run], [--skip-dry-run] # dry run mode # Default: fal Build the specified version of the package.
  10. 設計もろもろ part2 Job や Mailer も同様 全部 MVC で考えると Controller

    の責務 Controller は DDD でいうユースケース( アプリケ ーションサービス) 層
  11. 設計もろもろ part3 Rails だから実装ファイルの置き方は app/models/task/**_task.rb とか app 配下にディレクトリを切るのは MVC にレ

    イヤーを追加するのと同義 lib から model 参照するのはどうなの? lib/tasks から AR の model 参照したりしてる しいいいのでは