天天看點

Rails源代碼分析(2):分發器 Dispatcher

寫了兩遍~ 受不了這個網站

  1.       # Backward-compatible class method takes CGI-specific args. Deprecated
  2.       # in favor of Dispatcher.new(output, request, response).dispatch.
  3.       def dispatch(cgi = nil, session_options = CgiRequest::DEFAULT_SESSION_OPTIONS, output = $stdout)
  4.         new(output).dispatch_cgi(cgi, session_options)
  5.       end
  1.     def dispatch_cgi(cgi, session_options)
  2.       if cgi ||= self.class.failsafe_response(@output, '400 Bad Request') { CGI.new }
  3.         @request = CgiRequest.new(cgi, session_options)
  4.         @response = CgiResponse.new(cgi)
  5.         dispatch
  6.       end
  7.     rescue Exception => exception
  8.       failsafe_rescue exception
  9.     end
  1.     def dispatch
  2.       @@guard.synchronize do
  3.         begin
  4.           run_callbacks :before_dispatch
  5.           handle_request
  6.         rescue Exception => exception
  7.           failsafe_rescue exception
  8.         ensure
  9.           run_callbacks :after_dispatch, :enumerator => :reverse_each
  10.         end
  11.       end
  12.     end

1) run_callbacks :before_dispatch

2) handle_request

3) run_callbacks :after_dispatch

開發模式下會運作1) 和 3) 步驟:

  1.         unless cache_classes
  2.           # Development mode callbacks
  3.           before_dispatch :reload_application
  4.           after_dispatch :cleanup_application
  5.         end
  1.     def reload_application
  2.       # Run prepare callbacks before every request in development mode
  3.       run_callbacks :prepare_dispatch
  4.       Routing::Routes.reload
  5.       ActionView::TemplateFinder.reload! unless ActionView::Base.cache_template_loading
  6.     end
  7.     # Cleanup the application by clearing out loaded classes so they can
  8.     # be reloaded on the next request without restarting the server.
  9.     def cleanup_application
  10.       ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord)
  11.       Dependencies.clear
  12.       ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord)
  13.     end

主要工作:

  1.       def handle_request
  2.         @controller = Routing::Routes.recognize(@request)
  3.         @controller.process(@request, @response).out(@output)
  4.       end

識别controller,調用controller方法  @output 就是 $stdout