Skip to content

Commit

Permalink
Merge pull request #22 from benbalter/domain-parts
Browse files Browse the repository at this point in the history
Abstract out domain parsing
  • Loading branch information
benbalter committed Nov 28, 2013
2 parents 710d8ab + f60c0b9 commit 2e54de3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/gman.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ def list
# Returns a string with the FQDN; nil if there's an error.
def get_domain(text)

return nil if text.to_s.empty?
return nil if text.to_s.strip.empty?

text = text.downcase
text = text.downcase.strip
uri = Addressable::URI.parse(text)

if uri.host # valid https?://* URI
Expand All @@ -69,6 +69,19 @@ def get_domain(text)
end
end

# Helper function to return the public suffix domain object
#
# Supports all domainy strings (URLs, emails)
#
# Returns the domain object or nil, but no errors, never an error
def domain_parts(text)
begin
PublicSuffix.parse get_domain(text)
rescue
nil
end
end

# Is the given string in the form of a valid email address?
#
# Returns true if email, otherwise false
Expand Down
18 changes: 18 additions & 0 deletions test/test_gman.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"foo",
"",
nil,
" ",
]

class TestGman < Test::Unit::TestCase
Expand Down Expand Up @@ -87,4 +88,21 @@ class TestGman < Test::Unit::TestCase
end
end

should "not err out on invalid domains" do
assert_equal false, Gman.valid?("[email protected]")
assert_equal "act.gov.au", Gman.get_domain("[email protected]")
assert_equal nil, Gman.domain_parts("[email protected]")
end

should "return public suffix domain" do
assert_equal PublicSuffix::Domain, Gman.domain_parts("whitehouse.gov").class
assert_equal NilClass, Gman.domain_parts("foo.bar").class
end

should "parse domain parts" do
assert_equal "gov", Gman.domain_parts("[email protected]").tld
assert_equal "bar", Gman.domain_parts("foo.bar.gov").sld
assert_equal "bar", Gman.domain_parts("https://foo.bar.gov").sld
assert_equal "bar.gov", Gman.domain_parts("[email protected]").domain
end
end

0 comments on commit 2e54de3

Please sign in to comment.