Skip to content

Commit

Permalink
Refactor #internal_parse
Browse files Browse the repository at this point in the history
Add a guard for PublicSuffix makes #valid? simpler. Introduce a helper
method to keep things tidy.
  • Loading branch information
walro committed Oct 30, 2015
1 parent 2660ca7 commit 25460f2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
18 changes: 11 additions & 7 deletions lib/twingly/url.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,26 @@ def self.parse(potential_url)
end

def self.internal_parse(potential_url)
if potential_url.is_a?(Addressable::URI)
addressable_uri = potential_url
else
addressable_uri = Addressable::URI.heuristic_parse(potential_url)
end

addressable_uri = to_addressable_uri(potential_url)
raise Twingly::Error::ParseError if addressable_uri.nil?

public_suffix_domain = PublicSuffix.parse(addressable_uri.display_uri.host)
raise Twingly::Error::ParseError if public_suffix_domain.nil?

self.new(addressable_uri, public_suffix_domain)
rescue Addressable::URI::InvalidURIError, PublicSuffix::DomainInvalid => error
error.extend(Twingly::URL::Error)
raise
end

def self.to_addressable_uri(potential_url)
if potential_url.is_a?(Addressable::URI)
potential_url
else
Addressable::URI.heuristic_parse(potential_url)
end
end

def initialize(addressable_uri, public_suffix_domain)
unless addressable_uri.is_a?(Addressable::URI)
raise ArgumentError, "First parameter must be an Addressable::URI"
Expand Down Expand Up @@ -123,7 +127,7 @@ def normalized_path
end

def valid?
addressable_uri && public_suffix_domain && SCHEMES.include?(normalized_scheme)
SCHEMES.include?(normalized_scheme)
end

def <=>(other)
Expand Down
14 changes: 14 additions & 0 deletions spec/lib/twingly/url_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,20 @@ def valid_urls
end
end

describe ".to_addressable_uri" do
let(:adressable_uri) { Addressable::URI.parse(test_url) }

context "when given Addressable::URI" do
subject { described_class.to_addressable_uri(adressable_uri) }
it { is_expected.to eq(adressable_uri) }
end

context "when given string" do
subject { described_class.to_addressable_uri(test_url) }
it { is_expected.to eq(adressable_uri) }
end
end

describe "#initialize" do
context "when given input parameters of wrong types" do
it "raises an error" do
Expand Down

0 comments on commit 25460f2

Please sign in to comment.