Class: ApiHammer::ParsedBody

Inherits:
Object
  • Object
show all
Defined in:
lib/api_hammer/parsed_body.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body, content_type) ⇒ ParsedBody

Returns a new instance of ParsedBody.



7
8
9
10
11
# File 'lib/api_hammer/parsed_body.rb', line 7

def initialize(body, content_type)
  @body = body
  @content_type = content_type
  @media_type = ::Rack::Request.new({'CONTENT_TYPE' => content_type}).media_type
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



5
6
7
# File 'lib/api_hammer/parsed_body.rb', line 5

def body
  @body
end

#content_typeObject (readonly)

Returns the value of attribute content_type.



5
6
7
# File 'lib/api_hammer/parsed_body.rb', line 5

def content_type
  @content_type
end

#media_typeObject (readonly)

Returns the value of attribute media_type.



5
6
7
# File 'lib/api_hammer/parsed_body.rb', line 5

def media_type
  @media_type
end

Instance Method Details

#filtered_body(options) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/api_hammer/parsed_body.rb', line 23

def filtered_body(options)
  @filtered_body ||= begin
    if media_type == 'application/json'
      begin
        ApiHammer::Filtration::Json.new(body, options).filter
      rescue JSON::ParserError
        body
      end
    elsif media_type == 'application/x-www-form-urlencoded'
      ApiHammer::Filtration::FormEncoded.new(body, options).filter
    else
      body
    end
  end
end

#objectObject



13
14
15
16
17
18
19
20
21
# File 'lib/api_hammer/parsed_body.rb', line 13

def object
  instance_variable_defined?(:@object) ? @object : @object = begin
    if media_type == 'application/json'
      JSON.parse(body) rescue nil
    elsif media_type == 'application/x-www-form-urlencoded'
      CGI.parse(body).map { |k, vs| {k => vs.last} }.inject({}, &:update)
    end
  end
end