その他
    ホーム 技術発信 DoRuby Rakeタスクを追加する

    Rakeタスクを追加する

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    こんにちは。T氏です。

    今日は自作のRakeタスクを追加する方法をご紹介します。

    Rakeタスクを追加するには、まず [RAILS_ROOT]/lib/tasks にsample.rakeファイルを作成します。

    ファイルの中身の記述に関しては、

    desc “説明文”

    task “実行タスク名” do … end または => [“Rakeコマンド”]

    の2つをワンセットで書けばタスクが追加されます。

    ではsample.rakeファイルにタスクを書いてみます。内容は下記になります。

    それぞれ、hello world!と表示するコマンド、db:drop,db:createを実行するコマンド、db:migrate,db:fixtures:loadを実行するタスクとなります。

    # [RAILS_ROOT]/lib/tasks/sample.rake

    # rake hello_world
    desc "print hello world!" # description.
    task "hello_world" do # rake task name.
       p "hello world!" # print "hello world!"
    end

    namespace :sample do
      # rake sample:drop_and_create
      desc "drop and create db task."
      task "drop_and_create" => ["db:drop", "db:create"]

      # rake sample:migrate_and_fixtures
      desc "migrate and fixtures load task."
      task "migrate_and_fixtures" => ["db:migrate","db:fixtures:load"]
    end

    では、実際に追加されているか試してみましょう。

    $ rake --task
    (省略...)
    rake hello_world                                      # print hello world!
    (省略...)
    rake sample:drop_and_create                   # drop and create db task.
    rake sample:migrate_and_fixtures             # migrate and fixtures load task.
    $ rake hello_world
    "hello world!"

    Rakeタスクが追加されている事、実行された事が確認できましたでしょうか。

    皆さんも是非お試し下さい。