Class: Rack::Cors::Resource

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(public_resource, path, opts = {}) ⇒ Resource

Returns a new instance of Resource.



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/rack/cors.rb', line 120

def initialize(public_resource, path, opts={})
  self.path        = path
  self.methods     = ensure_enum(opts[:methods]) || [:get]
  self.credentials = opts[:credentials].nil? ? true : opts[:credentials]
  self.max_age     = opts[:max_age] || 1728000
  self.pattern     = compile(path)
  @public_resource = public_resource

  self.headers = case opts[:headers]
  when :any then :any
  when nil then nil
  else
    [opts[:headers]].flatten.collect{|h| h.downcase}
  end

  self.expose = opts[:expose] ? [opts[:expose]].flatten : nil
end

Instance Attribute Details

#credentialsObject

Returns the value of attribute credentials.



118
119
120
# File 'lib/rack/cors.rb', line 118

def credentials
  @credentials
end

#exposeObject

Returns the value of attribute expose.



118
119
120
# File 'lib/rack/cors.rb', line 118

def expose
  @expose
end

#headersObject

Returns the value of attribute headers.



118
119
120
# File 'lib/rack/cors.rb', line 118

def headers
  @headers
end

#max_ageObject

Returns the value of attribute max_age.



118
119
120
# File 'lib/rack/cors.rb', line 118

def max_age
  @max_age
end

#methodsObject

Returns the value of attribute methods.



118
119
120
# File 'lib/rack/cors.rb', line 118

def methods
  @methods
end

#pathObject

Returns the value of attribute path.



118
119
120
# File 'lib/rack/cors.rb', line 118

def path
  @path
end

#patternObject

Returns the value of attribute pattern.



118
119
120
# File 'lib/rack/cors.rb', line 118

def pattern
  @pattern
end

Instance Method Details

#match?(path) ⇒ Boolean

Returns:

  • (Boolean)


138
139
140
# File 'lib/rack/cors.rb', line 138

def match?(path)
  pattern =~ path
end

#process_preflight(env) ⇒ Object



142
143
144
145
# File 'lib/rack/cors.rb', line 142

def process_preflight(env)
  return nil if invalid_method_request?(env) || invalid_headers_request?(env)
  {'Content-Type' => 'text/plain'}.merge(to_preflight_headers(env))
end

#to_headers(env) ⇒ Object



147
148
149
150
151
152
153
154
155
# File 'lib/rack/cors.rb', line 147

def to_headers(env)
  x_origin = env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
  h = { 'Access-Control-Allow-Origin' => credentials ? env['HTTP_ORIGIN'] : public_resource? ? '*' : env['HTTP_ORIGIN'],
    'Access-Control-Allow-Methods'    => methods.collect{|m| m.to_s.upcase}.join(', '),
    'Access-Control-Expose-Headers'   => expose.nil? ? '' : expose.join(', '),
    'Access-Control-Max-Age'          => max_age.to_s }
  h['Access-Control-Allow-Credentials'] = 'true' if credentials
  h
end