0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】Rakeタスク

Posted at

はじめに

Rakeタスクの作成・実行方法についてまとめます。

Rakeタスクとは

  • 特定のタスクをコマンドラインで実行できる機能

作成方法

ファイルの作成

  • rails g task [名前空間] [タスク名] を実行しファイルを作成する
$ rails g task namespace_name task_name
  • lib/tasks配下に、[名前空間].rakeファイルが作成される
lib/tasks/namespace_name.rake
namespace :namespace_name do
  desc "TODO"
  task task_name: :environment do
  end

end

タスクの定義

  • 実行したい処理を定義する
lib/tasks/namespace_name.rake
namespace :namespace_name do
  desc "Hello, worldの出力"
  task task_name: :environment do
    puts "Hello, world!" # 実行したい処理をコードブロック内に書く
  end
end
namesace
  • 省略可
  • 名前空間を定義する事で、
    タスクをグループ化できる
desc
  • 省略可
  • タスクの説明文を定義する
task
  • タスク名と実行したい処理を定義する
  • :environmentを指定することで、Railsのクラスやモジュールを呼び出すことができるようになる

定義が出来たことを確認

  • 名前空間名、タスク名、説明文を確認できる
$ rake -vT | grep namespace_name
rake namespace_name:task_name          # Hello, world!の出力

タスクを実行

  • rake [名前空間]:[タスク名] でタスクを実行する
    • 名前空間を省略した場合は rake [タスク名]
$ rake namespace_name:task_name
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?