Class: Rack::AcceptOnly

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/accept-only.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, permitted_type = nil) ⇒ AcceptOnly

Returns a new instance of AcceptOnly.



3
4
5
6
7
# File 'lib/rack/accept-only.rb', line 3

def initialize(app, permitted_type = nil)
  raise "Keep the permitted content-type simple please" if permitted_type && permitted_type.match(%r{[*; ]})
  @app = app
  @permitted_type = permitted_type
end

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rack/accept-only.rb', line 9

def call(env)
  acceptable_types = get_acceptable_types(env)
  return @app.call(env) unless !acceptable_types.empty? || @permitted_type

  if !match_against_types?(acceptable_types, @permitted_type)
    return unacceptable(@permitted_type)
  end

  reply = @app.call(env)
  reply_type = reply[1]['Content-Type']
  
  return server_error unless reply_type
  
  if @permitted_type && reply_type != @permitted_type
    reply = server_error
  end
  
  if !match_against_types?(acceptable_types, reply_type)
    reply = unacceptable(reply_type)
  end

  reply
end

#get_acceptable_types(env) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/rack/accept-only.rb', line 33

def get_acceptable_types(env)
  return [] unless env['HTTP_ACCEPT']

  acceptable_types = env['HTTP_ACCEPT'].split(",")
  acceptable_types.collect do |type|
    temp = type.strip.split(";")[0].gsub("*", "(.+)")
    Regexp.new("^#{temp}$")
  end
end

#match_against_types?(types, string) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
49
50
# File 'lib/rack/accept-only.rb', line 43

def match_against_types?(types, string)
  return true unless !types.empty? && string

  types.each do |type|
    return true if string.match(type)
  end
  false
end

#server_errorObject



56
57
58
# File 'lib/rack/accept-only.rb', line 56

def server_error
  [500, {"Content-Length" => "0"}, [""]]
end

#unacceptable(supplyable_type) ⇒ Object



52
53
54
# File 'lib/rack/accept-only.rb', line 52

def unacceptable(supplyable_type)
  [406, {'Content-Type' => supplyable_type, "Content-Length" => "0"}, [""]]
end