24
23

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 5 years have passed since last update.

Rails で Rakeタスクを作る

Last updated at Posted at 2014-12-11

基本タスク

1. Rakeファイルを作成

ここではhelloというタスクを作成してみる。

$ rails g task hello

lib/taskshello.rakeが作成される。中身は

hello.rake
namespace :hello do
end

2. description(説明) と task(タスク)を記述

hello.rake
namespace :hello do
  desc "朝のあいさつ"
  task :morning do
    p "おはよー"
  end

  desc "昼のあいさつ"
  # モデルにアクセスする場合はenvironmentが必要
  task :noon => :environment do
    user = User.first
    p "こんにちは、#{user.name}さん"
  end
end

rakeタスクに追加されているか確認

$ rake -T

rake hello:morning
rake hello:noon

3. 実行してみる

$ rake hello:morning
"おはよー"

ログを出力する

hello.rake
namespace :hello do
  desc "朝の挨拶"
  task :morning do
    logger = Logger.new('log/development.log')
    logger.info('task morning が起動されました。')
    p "おはよー"
  end
end

namespaceを入れ子にする

hello.rake
namespace :hello do
  # タスクの説明

  namespace :morning do
    desc "丁寧なあいさつ"
    task :politely do
      p "おはようございます"
    end

    desc "フレンドリーなあいさつ"
    task :friendly do
      p "おはよー"
    end
  end
end
$ rake hello:morning:friendly
"おはよー"

$ rake hello:morning:politely
"おはようございます"

引数を渡す

環境変数で渡す

hello.rake
namespace :hello do
  desc "朝のあいさつ"
  task :morning do
    p ENV['GREETING']
    p ENV['TO_NAME']
  end
end
$ rake hello:morning GREETING="おっはよー" TO_NAME="太郎"
"おっはよー"
"太郎"
  • グローバルに定義されている環境変数と名前が被っていないか確認した方が良い。

タスクに直接渡す

hello.rake
namespace :hello do
  desc "朝のあいさつ"
  task :morning, 'GREETING', 'TO_NAME' do |task, args|
    p args['GREETING']
    p args['TO_NAME']
  end
end
$ rake hello:morning["おっはよー", "太郎"]
"おっはよー"
"太郎"
24
23
0

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
24
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?