Class: Rack::Adapter::Rails

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/adapter/rails.rb

Defined Under Namespace

Classes: CGIWrapper

Constant Summary collapse

FILE_METHODS =
%w(GET HEAD).freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Rails

Returns a new instance of Rails.



18
19
20
21
22
23
24
25
26
# File 'lib/rack/adapter/rails.rb', line 18

def initialize(options={})
  @root   = options[:root]         || Dir.pwd
  @env    = options[:environment]  || 'development'
  @prefix = options[:prefix]
  
  load_application
  
  @file_server = Rack::File.new(::File.join(RAILS_ROOT, "public"))
end

Instance Method Details

#call(env) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rack/adapter/rails.rb', line 65

def call(env)
  path        = env['PATH_INFO'].chomp('/')
  method      = env['REQUEST_METHOD']
  cached_path = (path.empty? ? 'index' : path) + ActionController::Base.page_cache_extension
  
  if FILE_METHODS.include?(method)
    if file_exist?(path)              # Serve the file if it's there
      return serve_file(env)
    elsif file_exist?(cached_path)    # Serve the page cache if it's there
      env['PATH_INFO'] = cached_path
      return serve_file(env)
    end
  end
  
  # No static file, let Rails handle it
  serve_rails(env)
end

#file_exist?(path) ⇒ Boolean

TODO refactor this in File#can_serve?(path) ??

Returns:

  • (Boolean)


44
45
46
47
# File 'lib/rack/adapter/rails.rb', line 44

def file_exist?(path)
  full_path = ::File.join(@file_server.root, Utils.unescape(path))
  ::File.file?(full_path) && ::File.readable_real?(full_path)
end

#load_applicationObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rack/adapter/rails.rb', line 28

def load_application
  ENV['RAILS_ENV'] = @env

  require "#{@root}/config/environment"
  require 'dispatcher'
  
  if @prefix
    if ActionController::Base.respond_to?('relative_url_root=')
      ActionController::Base.relative_url_root = @prefix # Rails 2.1.1
    else
      ActionController::AbstractRequest.relative_url_root = @prefix
    end
  end
end

#serve_file(env) ⇒ Object



49
50
51
# File 'lib/rack/adapter/rails.rb', line 49

def serve_file(env)
  @file_server.call(env)
end

#serve_rails(env) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rack/adapter/rails.rb', line 53

def serve_rails(env)
  request         = Request.new(env)
  response        = Response.new
  
  session_options = ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS
  cgi             = CGIWrapper.new(request, response)
    
  Dispatcher.dispatch(cgi, session_options, response)

  response.finish
end