Ramon Tayag Ramon Tayag - 1 year ago 135
Ruby Question

How to encode media in base64 given URL in Ruby

I'm trying to upload an image to PingFM. Their documentation says:

media – base64 encoded media data.

I can access this image via the URL. I tried (practically guessed) this:


But I get this error:

TypeError: can't convert Tempfile into String
from /usr/lib/ruby/1.8/base64.rb:97:in `pack'
from /usr/lib/ruby/1.8/base64.rb:97:in `encode64'
from (irb):19
from :0

Answer Source

The open method:


is returning a Tempfile object, while encode64 expects a String.

Calling read on the tempfile should do the trick:

ActiveSupport::Base64.encode64(open("http://image.com/img.jpg") { |io| io.read })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download