Class: Rack::Cors

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

Defined Under Namespace

Classes: Resource, Resources

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}, &block) ⇒ Cors

Returns a new instance of Cors.



5
6
7
8
9
10
11
12
13
14
# File 'lib/rack/cors.rb', line 5

def initialize(app, opts={}, &block)
  @app = app
  @logger = opts[:logger]

  if block.arity == 1
    block.call(self)
  else
    instance_eval(&block)
  end
end

Instance Method Details

#allow(&block) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/rack/cors.rb', line 16

def allow(&block)
  all_resources << (resources = Resources.new)

  if block.arity == 1
    block.call(resources)
  else
    resources.instance_eval(&block)
  end
end

#call(env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rack/cors.rb', line 26

def call(env)
  env['HTTP_ORIGIN'] = 'file://' if env['HTTP_ORIGIN'] == 'null'
  env['HTTP_ORIGIN'] ||= env['HTTP_X_ORIGIN']

  cors_headers = nil
  if env['HTTP_ORIGIN']
    debug(env) do
      [ 'Incoming Headers:',
        "  Origin: #{env['HTTP_ORIGIN']}",
        "  Access-Control-Request-Method: #{env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']}",
        "  Access-Control-Request-Headers: #{env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"
        ].join("\n")
    end
    if env['REQUEST_METHOD'] == 'OPTIONS'
      if headers = process_preflight(env)
        debug(env) do
          "Preflight Headers:\n" +
              headers.collect{|kv| "  #{kv.join(': ')}"}.join("\n")
        end
        return [200, headers, []]
      end
    else
      cors_headers = process_cors(env)
    end
  end
  status, headers, body = @app.call env
  headers = headers.merge(cors_headers) if cors_headers
  [status, headers, body]
end