Ruby's body_permitted? method giving "NoMethodError"

1.3k views Asked by At

I was going through ruby's Net::HTTP class. Every time I run this code from Net::HTTP doc

#!/usr/bin/ruby
require 'net/http'
uri = URI('http://example.com/index.html')
res = Net::HTTP.get_response(uri)

# Headers
res['Set-Cookie']            # => String
res.get_fields('set-cookie') # => Array
res.to_hash['set-cookie']    # => Array
puts "Headers: #{res.to_hash.inspect}"

# Status
puts res.code       # => '200'
puts res.message    # => 'OK'
puts res.class.name # => 'HTTPOK'

# Body
puts res.body if res.response_body_permitted?

I get this error

netHTTP.rb:18:in `<main>': undefined method `response_body_permitted?' for #<Net::HTTPOK 200 OK readbody=true> (NoMethodError)

Here is the response of code

Headers: {"accept-ranges"=>["bytes"], "cache-control"=>["max-age=604800"], "content-type"=>["text/html"], "date"=>["Sun, 07 Jun 2015 21:33:34 GMT"], "etag"=>["\"359670651\""], "expires"=>["Sun, 14 Jun 2015 21:33:34 GMT"], "last-modified"=>["Fri, 09 Aug 2013 23:54:35 GMT"], "server"=>["ECS (iad/18F0)"], "x-cache"=>["HIT"], "x-ec-custom-error"=>["1"], "content-length"=>["1270"]}
200
OK
Net::HTTPOK
netHTTP.rb:18:in `<main>': undefined method `response_body_permitted?' for #<Net::HTTPOK 200 OK readbody=true> (NoMethodError)

Is something wrong with my installation?

1

There are 1 answers

2
ivan.sim On BEST ANSWER

Looking at the source and docs of Ruby 2.1.x (and 2.2.0), the method that you need is body_permitted? So try with res.body_permitted?.

You can search through the source of older versions of Ruby on GitHub, by referring to their different tags. Pretty sure there is no such method in net/http as response_body_permitted?.

UPDATES

I can see how the documentation on body_permitted? can be a bit misleading when it says,

true if the response has a body.

First of all body_permitted? is a class method. So the correct way to use it is by doing something like:

irb(main)> Net::HTTPOK.body_permitted?
=> true
irb(main)> res.class.body_permitted?
=> true

Secondly, body_permitted? isn't telling you whether your particular response instance has a body. Instead, it's telling you whether the class of your response is permitted to have a body. Running these codes in irb will yield:

irb(main)> Net::HTTPOK.body_permitted?
=> true
irb(main)> Net::HTTPInformation.body_permitted?
=> false

Looking at the source of HTTPOK and HTTPInformation confirms our observation that body_permitted? is telling us whether body is permitted in each response class.

If you want to check if you response has a body, just do res.body.nil?. So something like:

puts res.body if res.class.body_permitted? && !res.body.nil?