Skip to content

Commit

Permalink
Provide explicit constructor to bypass URI.parse
Browse files Browse the repository at this point in the history
  • Loading branch information
dball committed Jan 13, 2011
1 parent 36c57e2 commit 5203e19
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 3 deletions.
6 changes: 5 additions & 1 deletion README.rdoc
Expand Up @@ -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

Expand All @@ -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,...
Expand Down
2 changes: 1 addition & 1 deletion 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"
Expand Down
11 changes: 10 additions & 1 deletion lib/data_uri/uri.rb
Expand Up @@ -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]
Expand Down
19 changes: 19 additions & 0 deletions test/test_data_uri.rb
Expand Up @@ -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
Expand Down

0 comments on commit 5203e19

Please sign in to comment.