&tag(Rails3/起動時の流れ); *目次 [#dba70d82] #contents *参考情報 [#e9eb92bf] *前提 [#f0eafa32] -Railsアプリを起動した時の処理の流れ。以下のコマンドで起動したときどういう風にWEBrickが起動されるか。 scrpt/rails server *script/rails [#rc490313] -アプリディレクトリのscript/railsがエントリーポイント。 #pre{{ APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands' }} *railties [#p9b0ae66] **rails/commands.rb [#p4645653] -ここでコマンドラインオプションが処理される。引数がserverの場合次の処理が実行される。 #pre{{ when 'server' # Change to the application's path if there is no config.ru file in current dir. # This allows us to run script/rails server from other directories, but still get # the main config.ru and properly set the tmp directory. Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru")) require 'rails/commands/server' Rails::Server.new.tap { |server| # We need to require application after the server sets environment, # otherwise the --environment option given to the server won't propagate. require APP_PATH Dir.chdir(Rails.application.root) server.start } }} ** rails/commands/server.rb [#e1066b72] -Rails::Serverは、Rack::Serverのサブクラスであることが分 module Rails class Server < ::Rack::Server }} *rack [#oe1d667c] ** rack/server.rb [#v4aa2b01] -Rack::Serverが実際にどのサーバーを使うかは以下の処理で決定されている。 #pre{{ def server @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default(options) end }} -options[:server]に使用するサーバーが設定されていない場合、Rack::Handler.default(options)によって決まる。 **rack/handler.rb [#t64bbdcb] -使用するデフォルトのサーバーを決定する処理。 Rack::Handler::Thinがエラーになれば、Rack::Handler::WEBrickが使われることが分かる。 #pre{{ def self.default(options = {}) # Guess. if ENV.include?("PHP_FCGI_CHILDREN") # We already speak FastCGI options.delete :File options.delete :Port Rack::Handler::FastCGI elsif ENV.include?("REQUEST_METHOD") Rack::Handler::CGI else begin Rack::Handler::Thin rescue LoadError Rack::Handler::WEBrick end end end }} *※ログ出力に関して [#gb489538] -WEBrickは、development.logにログを出力すると同時に標準出力にもログを表示している。 -この仕組は、railtiesのrails/rack/log_trailer.rbで行われているようだ。 #pre{{ def tail! return unless @cursor @file.seek @cursor unless @file.eof? contents = @file.read @cursor = @file.tell $stdout.print contents end end }} -ログファイルをシークしながら標準出力に差分を表示していることがわかる。