Class: Rack::Cors

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

Defined Under Namespace

Classes: Resource, Resources

Constant Summary collapse

VERSION =
"0.2.9"

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
15
16
17
# File 'lib/rack/cors.rb', line 5

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

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

Instance Method Details

#allow(&block) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/rack/cors.rb', line 19

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



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
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rack/cors.rb', line 29

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' and env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
      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
  if cors_headers
    headers = headers.merge(cors_headers)

    # http://www.w3.org/TR/cors/#resource-implementation
    unless headers['Access-Control-Allow-Origin'] == '*'
      vary = headers['Vary']
      headers['Vary'] = ((vary ? vary.split(/,\s*/) : []) + ['Origin']).uniq.join(', ')
    end
  end
  [status, headers, body]
end