Recommendations for processing binary data in Ruby?

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

In the code example below, I needed to send the binary via 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

Although this code seems to work well, it is probably not very idiomatic. How can I improve it?

+3
source share
1 answer

Then FileUtils copy_stream can be useful.

require 'fileutils'
fin = File.new('svarttag.jpg')
fout = File.new('blacktrain.jpg','w')
FileUtils.copy_stream(fin,fout)
fin.close
fout.close

Perhaps not quite what you requested, but if these are all the HTTP POST files you want to solve, then HTTPClient can do it for you:

require 'httpclient'    
HTTPClient.post 'http://nl.netlog.com/test', { :file => File.new('resp.der') }

I also heard that Nick Siegers multipart-post is good, but I have not used it.

Strike>

+3
source

Source: https://habr.com/ru/post/1741407/


All Articles