hypernova-ruby icon indicating copy to clipboard operation
hypernova-ruby copied to clipboard

to_json is used on request, but JSON.generate is used on blank_renderer which produces inconsistent results

Open davidbarratt opened this issue 3 years ago • 5 comments

When a request is made to https://github.com/airbnb/hypernova the to_json method is used: https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/faraday_request.rb#L8 but when the service does not respond, the data is serialized with JSON.generate https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/blank_renderer.rb#L24

Theoretically this should produce an identical result, but we have seen that this does not.

Could the latter instance be updated to use to_json as well?

davidbarratt avatar Oct 12 '22 18:10 davidbarratt

In what way does it not?

ljharb avatar Oct 12 '22 20:10 ljharb

In what way does it not?

Objects that aren't hashes will return the to_s value.

Indeed, the documentation says:

JSON.generate only allows objects or arrays to be converted to JSON syntax. to_json, however, accepts many Ruby classes even though it acts only as a method for serialization

davidbarratt avatar Oct 12 '22 21:10 davidbarratt

So a fix could be JSON.generate(obj.respond_to?(:to_json) ? data.to_json : data)? That seems reasonable.

ljharb avatar Oct 12 '22 21:10 ljharb

So a fix could be JSON.generate(obj.respond_to?(:to_json) ? data.to_json : data)? That seems reasonable.

I believe to_json returns a string, so I don't think passing it into JSON.generate() would work. If we are calling to_json exclusively elsewhere, it seems like it could simply be changed to:

data.to_json.gsub(/&/, '&').gsub(/>/, '>') 

right?

davidbarratt avatar Oct 12 '22 23:10 davidbarratt

ah right I’m thinking of .as_json

ljharb avatar Oct 13 '22 03:10 ljharb