kasei_sanのブログ

かせいさんのIT系のおぼえがきです。胡乱の方はnoteとtwitterへ

Railsガイド Rails のコマンドラインツール 2.10 カスタムRakeタスク

Rails のコマンドラインツール | Rails ガイド

ジェネレータ

rails generate task で生成

$ rails generate task sample_task                                                                       create  lib/tasks/sample_task.rake
namespace :sample_task do
end

Rakeタスクの基本形

namespace :sample_task do
  desc 'あいさつ' # 説明
  task :hello do
    p "hello"
  end 
end
rake -T | grep hello
rake sample_task:hello                  # あいさつ
$ rake sample_task:hello
"hello"

引数

namespace :sample_task do
  desc 'なんか言う'
  task :say, :message do |task, args|
    puts "#{args[:message]}"
  end
end
$ rake -T | grep say
rake sample_task:say[message]           # なんか言う
$ rake "sample_task:say[hello]"
hello

呼び出し方が気になる...

ActiveRecord関係の機能を使う

namespace :sample_task do
  desc 'ユーザを取得'
  task :find_user, [:name] => :environment do |task, args|
    p User.where(:name => "#{args[:name]}").first
  end
end

参考