1

I have a method which outputs api reponse. The response could be either a JSON response or non-JSON response. For JSON response, my code is as follows:


def process
  if success?
    JSON.parse(response.body)
  else
    handle_failure
  end
end

And for non-JSON response, I used 'eval' as:


def process
  if success?
    eval(response.body)
  else
    handle_failure
  end
end

But since response could be anything, how can I make sure that it prints the response in both case?

Thanks

Moriarty
  • 159
  • 2
  • 16

1 Answers1

2

Using the method from Checking if a string is valid json before trying to parse it?, define a method to check if the body is a JSON or not:

def valid_json?(json)
  JSON.parse(json)
  return true
rescue JSON::ParserError => e
  return false
end

In your class above you can then do:

def process
  valid_json?(response.body) ? process_json : process_non_json
end

def valid_json?(json)
  JSON.parse(json)
  return true
rescue JSON::ParserError => e
  return false
end

def process_json
  if success?
    JSON.parse(response.body)
  else
    handle_failure
  end
end

def process_non_json
  if success?
    eval(response.body)
  else
    handle_failure
  end
end
Mark
  • 6,112
  • 4
  • 21
  • 46