tags:

views:

84

answers:

1

What are the best practices for reading and writing binary data in Ruby?

In the code sample below I needed to send a binary file using over HTTP (as POST data):

class SimpleHandler < Mongrel::HttpHandler
  def process(request, response)
    response.start(200) do |head,out|
      head["Content-Type"] = "application/ocsp-responder"
      f = File.new("resp.der", "r")
      begin
        while true
          out.syswrite(f.sysread(1))
        end
      rescue EOFError => err
        puts "Sent response."
      end
    end
  end
end

While this code seems to do a good job, it probably isn't very idiomatic. How can I improve it?

+1  A: 
Jonas Elfström
I added some extra context to the sample code. As you can see I have to use the IO object provided by the Mongrel framwork, so I can't just use a HTTPClient.post instead.
StackedCrooked
When opening binary files you should always add the "binary" modifier (`b`) to the filemode. So, above you should have `File.new('svarttag.jpg', 'rb')` and `File.new('blacktrain.jpg', 'wb')`.
Jörg W Mittag