おぴよの気まぐれ日記

おぴよの気まぐれ日記

岡山やプログラミング、ファッションのこと、子育てや人生、生き方についての備忘録。

【Ruby on Rails】Rakeタスクを使えば様々な処理が自動化出来る?(初心者向け)

今日は様々な場面で活躍するrakeタスクの作り方と実行方法をまとめてみます。

Rakeとは

そもそもRakeですが、Rubyで書かれたコードをタスクとして作成しておき必要に応じて呼び出し実行する事が出来る機能です。

rakeタスクを利用する場面としては、こんなのが有ります。

  • 何かしらのデータの連携
  • データベースのバックアップ
  • 定期的にデータを更新、削除する

Rakeタスクの作り方

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

rakeファイル

# lib/tasks/herro.rake
namespace :hello do
  task :world => :environment do
    hw = HelloWorld.new
    puts hw.hoge
  end
end

大事なのが、namespacetaskで定義した名称です。ここがrakeタスクを実行する時に使います。

:environmentっていうのは、とりあえずおまじないだと理解してます。

タスクを実行するクラスファイル

# lib/hello_world.rb
class HelloWorld
  def hoge
   "Hello World"
  end
end

こちらは単純なクラスファイルです。hogeメソッドが呼ばれるとHello Worldを返すだけのクラスです。

注意点としては、ファイル名とクラス名は合わせて下さい。

オートロード対象となるパスの追加

ここハマりポイントです。私は30分ほど悩んでも分からず教えてもらいました。

タスクを実行するファイルをlib/配下に置きましたが、設定を変更しないとrailsの世界から見えないだそうです。

# config/application.rb
config.autoload_paths += %W(#{config.root}/lib)

Rakeタスクの実行方法

$ rake hello:world
Hello World

Rakeタスクの確認方法

定義されているrakeタスクの一覧を表示するコマンドがあるみたいです。

$ rake --tasks
rake about                              # List versions of all Rails frameworks and the environment
rake app:template                       # Applies the template supplied by LOCATION=(/path/to/template) or URL
rake app:update                         # Update configs and some other initially generated files (or use just update:configs or update:bin)
rake assets:clean[keep]                 # Remove old compiled assets
rake assets:clobber                     # Remove compiled assets
rake assets:environment                 # Load asset compile environment
rake assets:precompile                  # Compile all the assets named in config.assets.precompile
rake cache_digests:dependencies         # Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake cache_digests:nested_dependencies  # Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to creating ...
rake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to dropping the de...
rake db:environment:set                 # Set the environment value for the database
rake db:fixtures:load                   # Loads fixtures into the current environment's database
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status                  # Display status of migrations
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear              # Clears a db/schema_cache.dump file
rake db:schema:cache:dump               # Creates a db/schema_cache.dump file
rake db:schema:dump                     # Creates a db/schema.rb file that is portable against any DB supported by Active Record
rake db:schema:load                     # Loads a schema.rb file into the database
rake db:seed                            # Loads the seed data from db/seeds.rb
rake db:setup                           # Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)
rake db:structure:dump                  # Dumps the database structure to db/structure.sql
rake db:structure:load                  # Recreates the databases from the structure.sql file
rake db:version                         # Retrieves the current schema version number
rake dev:cache                          # Toggle development mode caching on/off
rake initializers                       # Print out all defined initializers in the order they are invoked by Rails
rake log:clear                          # Truncates all/specified *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
rake middleware                         # Prints out your Rack middleware stack
rake notes                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
rake notes:custom                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
rake restart                            # Restart app by touching tmp/restart.txt
rake routes                             # Print out all defined routes in match order, with names
rake secret                             # Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions)
rake stats                              # Report code statistics (KLOCs, etc) from the application or engine
rake time:zones[country_or_offset]      # List all time zones, list by two-letter country code (`rails time:zones[US]`), or list by UTC offset (`rails time:zones[-8]`)
rake tmp:clear                          # Clear cache and socket files from tmp/ (narrow w/ tmp:cache:clear, tmp:sockets:clear)
rake tmp:create                         # Creates tmp directories for cache, sockets, and pids

まとめ

rakeタスクを使うことで様々な処理を作成しておけば色々な場面で何度も使う事が出来るので非常に便利ですし、業務でも良く利用します。

また、これと合わせて定期実行の仕組みを入れて上げると「毎日4時にDBバックアップを行う」などが出来るようになります!

今日はこんな感じです。