71
52

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.

rakeタスクを定義するときのおまじない :environment がやっていること

Last updated at Posted at 2015-10-11

おまじない

task test: :environment do
  # task
end

railsでDBアクセスしたりするrakeタスクを定義するときに↑の様な感じで:environmentを指定する必要があるが、
その:environmentが何をしているのか不思議だったので調べた

コードを追ってみた(要所だけ)

# https://github.com/rails/rails/blob/master/railties/lib/rails/application.rb#L432-L441
def run_tasks_blocks(app) #:nodoc:
  railties.each { |r| r.run_tasks_blocks(app) }
  super
  require "rails/tasks"
  task :environment do
    ActiveSupport.on_load(:before_initialize) { config.eager_load = false }

    require_environment!
  end
end

railsのコード内に定義されている、
:environmentという名のrakeタスクが呼ばれる

# https://github.com/rails/rails/blob/master/railties/lib/rails/application.rb#L317-L320
def require_environment! #:nodoc:
  environment = paths["config/environment"].existent.first
  require environment if environment
end

Rails.rootにあるconfig/environmentrequireされる

# config/environment.rb

# Load the Rails application.
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
Rails.application.initialize!

Rails.application.initialize!が呼ばれる

まとめ

三行で書くと

:enviromentというrakeタスクを実行して
config/environment.rbrequireして
Rails.application.initialize!してた

なので、DBやモデルにアクセスするとき以外にも使える

71
52
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
71
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?