--- layout: old_post title: Rails環境で初期化処理を追加したい場合どこに記述するべきか? permalink: /tatsuya/show/261-rails ---
Environments and the Rails initialisation process
Railsの環境がどんな手順で起動するか、初期化処理を組み込みたい場合どこに書くべきか、という記事があったので試してみる。この記事によると主に以下の順番があると、RAILS_ENV=developmentの場合
まず始め : /public/dispatch.fcgi をfcgiが実行 -> require File.dirname(__FILE__) + "/../config/environment"
この7点のどこかに初期設定処理を書く事ができると、でどこに書くかは「時と場合による」だって。う~む、ここで面白いのはconfig.after_initializeとconfig.to_prepareだろうか。これはそれぞれ↓な感じ
Railsの初期設定が完了してから行ないたい処理、しかもdevelopment / test / production特有の処理を記述したい場合はdevelopment.rbとかに
config.after_initialize do #好きな処理 end
とか書けばGoodだと。逆に環境に依存しない処理なら、6. environment.rbの最後で良いのかな。
環境設定というより、HTTPリクエスト毎に毎回実行したい処理を記述する。どんな処理だろ?アクセス数のカウントとか良いかも。例えばproduction.rbとかに
config.to_prepare do Access.countUp end
とか書けば良いみたい。
それぞれのポイントで p "hogehoge" とかいれて試した結果はこれ↓、development.rbとかって2回起動してて良いの?
** Starting Mongrel listening at 0.0.0.0:3000 ** Starting Rails with development environment ... "[envilonment.rb-start] 1" "[boot.rb] 2" "[environment.rb-Rails::Initializer.run] 3" "[development.rb] 4" "[development.rb] 4" "[development.rb-after_initialize] 5" "[environment.rb-end] 6" ** Rails loaded. ** Loading any Rails specific GemPlugins ** Signals ready. INT => stop (no restart). ** Mongrel available at 0.0.0.0:3000 127.0.0.1 - [Sun, 11 Feb 2007 06:59:28 GMT] "GET /rsses/1 HTTP/1.1" "[development.rb-to_prepare] 7"