Class: Raccept
- Inherits:
-
Object
- Object
- Raccept
- Defined in:
- lib/raccept.rb
Instance Attribute Summary collapse
-
#app ⇒ Object
readonly
Returns the value of attribute app.
Instance Method Summary collapse
- #call(env) ⇒ Object
- #convert(format, body) ⇒ Object
- #header_list ⇒ Object
-
#initialize(app, options = {}) ⇒ Raccept
constructor
A new instance of Raccept.
- #legal_rack_body?(body) ⇒ Boolean
Constructor Details
#initialize(app, options = {}) ⇒ Raccept
Returns a new instance of Raccept.
9 10 11 |
# File 'lib/raccept.rb', line 9 def initialize(app, = {}) @app = app end |
Instance Attribute Details
#app ⇒ Object (readonly)
Returns the value of attribute app.
8 9 10 |
# File 'lib/raccept.rb', line 8 def app @app end |
Instance Method Details
#call(env) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/raccept.rb', line 13 def call(env) result = app.call(env) body = result[2] # If body is already a string or array with string(s) pass it along. return result if legal_rack_body?(body) accepts_headers = env['HTTP_ACCEPT'].sub(/\;.+/,'').split(',') accepts_headers.each do |accepts| if header_list[accepts] return [result[0], result[1], convert(header_list[accepts], body) ] end end result # apparently nothing matched, so return untouched result end |
#convert(format, body) ⇒ Object
40 41 42 43 44 45 46 47 |
# File 'lib/raccept.rb', line 40 def convert(format, body) case format when :json body.to_json when :xml body.to_xml end end |
#header_list ⇒ Object
49 50 51 52 53 54 55 56 |
# File 'lib/raccept.rb', line 49 def header_list { 'application/json' => :json, 'text/json' => :json, 'application/xml' => :xml, 'text/xml' => :xml } end |
#legal_rack_body?(body) ⇒ Boolean
32 33 34 35 36 37 38 |
# File 'lib/raccept.rb', line 32 def legal_rack_body?(body) if body.kind_of?(String) true elsif body.respond_to?(:each) body.collect {|element| element.class }.uniq == [String] end end |