Skip to content

Commit

Permalink
Simple URI component validation
Browse files Browse the repository at this point in the history
Pending a URI::GID < URI::Generic subclass to handle it for us.
  • Loading branch information
jeremy committed Aug 16, 2014
1 parent a06bc98 commit 37beb80
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/global_id/global_id.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ def parse(gid)

def initialize(gid)
@uri = gid.is_a?(URI) ? gid : URI.parse(gid)
@app = @uri.host
@model_name, @model_id = @uri.path.split('/')[1, 2]
@app, @model_name, @model_id = extract_uri_components(@uri)
end

def find
Expand All @@ -47,4 +46,18 @@ def to_s
uri.to_s
end

private
PATH_REGEXP = %r(\A/([^/]+)/([^/]+)\z)

# Pending a URI::GID to handle validation
def extract_uri_components(uri)
raise ArgumentError, "Not a gid:// URI scheme: #{uri.inspect}" unless @uri.scheme == 'gid'
raise ArgumentError, "Missing app name: #{uri.inspect}" unless @uri.host

if @uri.path =~ PATH_REGEXP
[ @uri.host, $1, $2 ]
else
raise ArgumentError, "Expected a /Model/id URI path: #{uri.inspect}"
end
end
end
24 changes: 24 additions & 0 deletions test/cases/global_id_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,30 @@ class GlobalIDTest < ActiveSupport::TestCase
end
end

class URIValidationTest < ActiveSupport::TestCase
test 'scheme' do
assert_raise ArgumentError do
GlobalID.new('gyd://app/Person/1')
end
end

test 'app' do
assert_raise ArgumentError do
GlobalID.new('gid://Person/1')
end
end

test 'path' do
assert_raise ArgumentError do
GlobalID.new('gid://app/Person')
end

assert_raise ArgumentError do
GlobalID.new('gid://app/Person/1/2')
end
end
end

class GlobalIDCreationTest < ActiveSupport::TestCase
setup do
@uuid = '7ef9b614-353c-43a1-a203-ab2307851990'
Expand Down

0 comments on commit 37beb80

Please sign in to comment.