Class: Rack::Client::Parser::JSON

Inherits:
Base
  • Object
show all
Defined in:
lib/rack/client/parser/json.rb

Constant Summary

Constants inherited from Base

Base::CONTENT_TYPE

Instance Method Summary collapse

Methods inherited from Base

content_type, lookup, type_table

Instance Method Details

#decode(body) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rack/client/parser/json.rb', line 20

def decode(body)
  BodyCollection.new do |collection|
    begin
      data = if body.respond_to? :read
               body.read
             elsif body.respond_to? :to_path
               File.read(body.to_path)
             else
               io = StringIO.new

               body.each do |part|
                 io << part
               end

               io.rewind
               io.read
             end

      case result = ::JSON.parse(data)
      when Array then result.each {|object| collection << object }
      else collection << result
      end

      collection.finish
    ensure
      body.close if body.respond_to? :close
    end
  end
end

#encode(input) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/rack/client/parser/json.rb', line 10

def encode(input)
  output = StringIO.new

  input.each do |object|
    ::JSON.dump(object, output)
  end

  output
end