From 5203e193226728c3d57525e898a47508be3d75e2 Mon Sep 17 00:00:00 2001 From: Donald Ball Date: Thu, 13 Jan 2011 16:29:35 -0500 Subject: [PATCH] Provide explicit constructor to bypass URI.parse --- README.rdoc | 6 +++++- data_uri.gemspec | 2 +- lib/data_uri/uri.rb | 11 ++++++++++- test/test_data_uri.rb | 19 +++++++++++++++++++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/README.rdoc b/README.rdoc index 6b64473..87b7596 100644 --- a/README.rdoc +++ b/README.rdoc @@ -13,7 +13,7 @@ a line. require 'data_uri' - uri = URI.parse('data:image/gif;base64,...') + uri = URI::Data.new('data:image/gif;base64,...') uri.content_type # image/gif uri.data # Base64 decoded data @@ -32,6 +32,10 @@ add if anyone's interested. == Features & Limitations +URI.parse knows about URI::Data, but unfortunately, its regexp for splitting +URIs into components maxes out at 92 characters for an opaque URI, which is +far too small to be useful for data URIs. + It accepts URIs with charset MIME parameters: data:text/html;charset=utf-8,... diff --git a/data_uri.gemspec b/data_uri.gemspec index 45fabc7..11e6a8f 100644 --- a/data_uri.gemspec +++ b/data_uri.gemspec @@ -1,6 +1,6 @@ Gem::Specification.new do |s| s.name = "data_uri" - s.version = "0.0.2" + s.version = "0.0.3" s.author = "Donald Ball" s.email = "donald.ball@gmail.com" s.homepage = "http://github.com/dball/data_uri" diff --git a/lib/data_uri/uri.rb b/lib/data_uri/uri.rb index d89eded..f513633 100644 --- a/lib/data_uri/uri.rb +++ b/lib/data_uri/uri.rb @@ -9,7 +9,16 @@ class Data < Generic attr_reader :content_type, :data def initialize(*args) - super(*args) + if args.length == 1 + uri = args.first.to_s + unless uri.match(/^data:/) + raise 'Invalid Data URI: ' + args.first.inspect + end + @scheme = 'data' + @opaque = uri[5 .. -1] + else + super(*args) + end @data = @opaque if md = MIME_TYPE_RE.match(@data) @content_type = md[1] diff --git a/test/test_data_uri.rb b/test/test_data_uri.rb index a6009f0..66faf40 100644 --- a/test/test_data_uri.rb +++ b/test/test_data_uri.rb @@ -68,6 +68,25 @@ end + describe "a big data binary data URI" do + + before do + @data = Array.new(100000) { rand(256) }.pack('c*') + @raw = "data:application/octet-stream;base64,#{Base64.encode64(@data).chop}" + end + + it "shouldn't be parsed by URI.parse because the ABS_URI regexp is silly" do + uri = URI.parse(@raw) + assert uri.data != @data + end + + it "should be parsed by URI::Data.new" do + uri = URI::Data.new(@raw) + assert uri.data == @data + end + + end + end describe "building" do