Question

I'm learning Ruby.

I have some code that uses the HTTParty library to download some data. The remote server does not correctly define the content-type so the response is not parsed (as JSON) automatically.

The JSON looks something like this:

{"response":{ ............ }}

In the code is the following line:

if resp['response'] == 'response'

In the case that the response is automatically parsed this behaves as expected and { .......... } from the original JSON would be returned. In the case that it is not parsed it returns the string response and I cannot figure out why it does that.

Which feature of the HTTParty library causes it to return the string response? A different request that results in plain text data returns Nil when trying to access ['response'].

Was it helpful?

Solution

This is how I now understand it. The resp['response'] tries to call the [] method on the resp object but since this is not defined the method_missing method is invoked

# the method_missing from HTTParty::Response
def method_missing(name, *args, &block)
  if parsed_response.respond_to?(name)
    $stdout.puts parsed_response.class.inspect
    $stdout.puts parsed_response.inspect
    parsed_response.send(name, *args, &block)
  elsif response.respond_to?(name)
    response.send(name, *args, &block)
  else
    super
  end
end

In the case where the JSON is not parsed the parsed_response is actually a String. The String class in Ruby defines [] such that when given a string like response as the argument the same string is returned back but only in the case that it exists within the entire string.

Since the JSON string did contain "response" the response value was returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top