data: URIs in Ruby
Anne van Kesteren’s got a cute little demonstration of <canvas/>. I particularly like the idea of saving something to a data: URI; one of those cool little things about the Web that doesn’t get much attention.
I also like favicons, and not having to use a general-purpose image manipulation program to create them. Hence, a teeny-tiny Camping mount which will convert an image/png data: URI into a favicon (example). At its heart is a class for handling data: URIs that goes something like this:
module URI
class Data < Generic
attr_reader :mime_type, :data
def read; data; end
def initialize(scheme, userinfo, host, port,
registry, path, opaque, query, fragment)
super
notdata, data = opaque.split(",", 2)
match = URI.decode(notdata).match(/^(.*?)(;base64)?$/)
@mime_type = match[1]
if @mime_type.empty?
@mime_type = "text/plain;charset=US-ASCII"
elsif @mime_type[0] == ?;
@mime_type = "text/plain#{@mime_type}"
end
@data = unless match[2].nil?
Base64.decode64(data)
else
URI.decode(data)
end
end
end
@@schemes["DATA"] = Data
end
It’s not a complete implementation of RFC 2397; some legitimate URIs (eg. data:text/plain;charset=iso-8859-7,%be%fg%be) can’t be parsed without fiddling around with uri.rb’s internals.
(BTW, the favicon is much shrunken from Paintr’s canvas; you’ll have to go over your lines several times to get something you can see.)