Rakeタスク

こんにちは、スバルです。今回は、Rakeタスクについて学習していきたいと思います。

Rakeとは

Rubyで書かれたシンプルなビルドツールのことです。

Rakeコマンドの種類

rake —helpをCUIに打つと、ズラーっとコマンドが出てきます。

$ bundle exec rake --help
rake [-f rakefile] {options} targets...

Options are ...
        --backtrace=[OUT]            Enable full backtrace.  OUT can be stderr (default) or stdout.
        --comments                   Show commented tasks only
        --job-stats [LEVEL]          Display job statistics. LEVEL=history displays a complete job list
        --rules                      Trace the rules resolution.
        --suppress-backtrace PATTERN Suppress backtrace lines matching regexp PATTERN. Ignored if --trace is on.
    -A, --all                        Show all tasks, even uncommented ones (in combination with -T or -D)
    -B, --build-all                  Build all prerequisites, including those which are up-to-date.
    -D, --describe [PATTERN]         Describe the tasks (matching optional PATTERN), then exit.
    -e, --execute CODE               Execute some Ruby code and exit.
    -E, --execute-continue CODE      Execute some Ruby code, then continue with normal task processing.
    -f, --rakefile [FILENAME]        Use FILENAME as the rakefile to search for.
    -G, --no-system, --nosystem      Use standard project Rakefile search paths, ignore system wide rakefiles.
    -g, --system                     Using system wide (global) rakefiles (usually '~/.rake/*.rake').
    -I, --libdir LIBDIR              Include LIBDIR in the search path for required modules.
    -j, --jobs [NUMBER]              Specifies the maximum number of tasks to execute in parallel. (default is number of CPU cores + 4)
    -m, --multitask                  Treat all tasks as multitasks.
    -n, --dry-run                    Do a dry run without executing actions.
    -N, --no-search, --nosearch      Do not search parent directories for the Rakefile.
    -P, --prereqs                    Display the tasks and dependencies, then exit.
    -p, --execute-print CODE         Execute some Ruby code, print the result, then exit.
    -q, --quiet                      Do not log messages to standard output.
    -r, --require MODULE             Require MODULE before executing rakefile.
    -R, --rakelibdir RAKELIBDIR,     Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib')
        --rakelib
    -s, --silent                     Like --quiet, but also suppresses the 'in directory' announcement.
    -t, --trace=[OUT]                Turn on invoke/execute tracing, enable full backtrace. OUT can be stderr (default) or stdout.
    -T, --tasks [PATTERN]            Display the tasks (matching optional PATTERN) with descriptions, then exit. -AT combination displays all of tasks contained no description.
    -v, --verbose                    Log message to standard output.
    -V, --version                    Display the program version.
    -W, --where [PATTERN]            Describe the tasks (matching optional PATTERN), then exit.
    -X, --no-deprecation-warnings    Disable the deprecation warnings.
    -h, -H, --help                   Display this help message.

railsコマンドに統一

なお、Rails5.0からRakeコマンドはrailsコマンドに統一されたようです

railsguides.jp

Rakeタスクとは

行いたい処理をコマンドプロンプト上から実行できる機能の一つです。CSVnのインポートやデータの整理など、アプリケーション側にインターフェイスを設けていない処理を実行する際などに用いられます。

Rakeタスクの作り方

一から自分で書くこともできるみたいですが、先人の作った型を踏襲した方が効率がいい、かつタイポを防げるので、比較的複雑なタスクも簡単に書くことができます。

Rakeファイルは普通のRubyスクリプトの文法と同じように書くことができるので、工夫次第でRubyにできることならなんでもできます。

今回は、Hello Worldとコンソール上に表示するrakeタスクを作成してみます。

$ bundle exec rails g task task_sample

task_sampleの部分は任意の名前で大丈夫です。

すると、lib/tasks/task_sample.rakeが生成されるのでこのファイルに書いていきます

# lib/tasks/task_sample.rake
namespace :task_sample do
  desc "実行処理の説明"
  task :sample do
    puts "Hello World"
  end
end

用語

desc: describeのことで、今回設定する処理の説明を書きます。

task :sample do :sampleシンボルメソッド を呼び出されたときにHello Worldが出力されるように定義しています。

注意点

ファイル名とクラス名は合わせる必要がある。

作ったRakeファイルを確認

$ bundle exec rake -vT

#出力結果がズラ〜と並びます

rake task_sample:sample                    # 実行処理の説明

Rakeタスクの実行方法

下記コマンドを打つと、lib/tasks/task_sample.rakeで定義したtaskメソッドが実行され、Hello Worldが出力されました。

$ bundle exec rake task_sample:task
Hello World

DBに接続する場合

lib/tasks/task_sample.rake

#モデルにアクセスする場合は :environment を指定します

namespace :task_sample do
  desc "task_sample_use_model"
  task :task_model => :environment do
    puts User.first().to_yaml  #Userモデルを参照する!
  end
end

実行してみると、下記のようになります。

$ bundle exec rake task_sample:task_model
--- !ruby/object:User
concise_attributes:
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: id
  value_before_type_cast: 1
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: name
  value_before_type_cast: admin
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: crypted_password
  value_before_type_cast: "$2a$10$5EwlnJ1BDI0esbb9YYsrBem0qvP.oCRnpMcggtQ.nxWtHQ5gwNpee"
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: role
  value_before_type_cast: 20
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: created_at
  value_before_type_cast: '2021-08-25 22:14:10.047807'
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: updated_at
  value_before_type_cast: '2021-08-28 13:17:50.374367'
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: deleted_at
new_record: false
active_record_yaml_version: 2

ちなみに今回bundle execと書く理由は、rakeコマンドをGemfile.lockに書かれているバージョンのgemで動かしたいからです。

bundle execをつけないと、Gemfile.lockに基づかずにgemのバージョンが決定される一方で、bundle execをつけると、Gemfile.lockに書かれているバージョンのgemが動くそうです。

試しにbundle execをつけないで動かしてみます。

$ rake -T
rake aborted!
Gem::LoadError: You have already activated rake 13.0.3, but your Gemfile requires rake 13.0.1. 
Prepending `bundle exec` to your command may solve this.

bundle exec をつけてくださいとエラーが出てしまいました。bundle execをつけないで上記コマンドを実行したいときは、Gemfileに記載しているrakeのバージョンと実際に実行しているrakeのバージョンを同じにするようにしましょう。

ActiveModel::Attributesを使う - Qiita

rake と bundle exec rake の違い - Qiita