Skip to content

Commit

Permalink
added the basic url canonicalization and representation code
Browse files Browse the repository at this point in the history
  • Loading branch information
pauldix committed Dec 10, 2009
1 parent 7f7f16b commit f80c552
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/domainatrix.rb
@@ -1,6 +1,7 @@
$LOAD_PATH.unshift(File.dirname(__FILE__)) unless $LOAD_PATH.include?(File.dirname(__FILE__))

require 'domainatrix/domain_parser.rb'
require 'domainatrix/url.rb'

module Domainatrix
VERSION = "0.0.1"
Expand Down
27 changes: 27 additions & 0 deletions lib/domainatrix/url.rb
@@ -0,0 +1,27 @@
module Domainatrix
class Url
attr_reader :tld, :domain, :subdomain, :path

def initialize(attrs = {})
@tld = attrs[:tld]
@domain = attrs[:domain]
@subdomain = attrs[:subdomain]
@path = attrs[:path]
end

def canonical(options = {})
url = "#{@tld}.#{@domain}"
if @subdomain
if options[:include_www]
url << ".#{@subdomain}"
else
sub_without_www = @subdomain.gsub(/^www/, "")
url << (sub_without_www.start_with?(".") ? sub_without_www : ".#{sub_without_www}") unless sub_without_www.empty?
end
end
url << @path if @path

url
end
end
end
36 changes: 36 additions & 0 deletions spec/domainatrix/url_spec.rb
@@ -0,0 +1,36 @@
require File.dirname(__FILE__) + '/../spec_helper'

describe "url" do
it "has the tld" do
Domainatrix::Url.new(:tld => "net").tld.should == "net"
end

it "has the domain" do
Domainatrix::Url.new(:domain => "pauldix").domain.should == "pauldix"
end

it "has the subdomain" do
Domainatrix::Url.new(:subdomain => "foo").subdomain.should == "foo"
end

it "has the path" do
Domainatrix::Url.new(:path => "/asdf.html").path.should == "/asdf.html"
end

it "canonicalizes the url without www" do
Domainatrix::Url.new(:subdomain => "www", :domain => "pauldix", :tld => "net").canonical.should == "net.pauldix"
Domainatrix::Url.new(:subdomain => "www.foo", :domain => "pauldix", :tld => "net").canonical.should == "net.pauldix.foo"
end

it "canonicalizes the url with www" do
Domainatrix::Url.new(:subdomain => "www", :domain => "pauldix", :tld => "net").canonical(:include_www => true).should == "net.pauldix.www"
end

it "canonicalizes the url with the path" do
Domainatrix::Url.new(:subdomain => "foo", :domain => "pauldix", :tld => "net", :path => "/hello").canonical.should == "net.pauldix.foo/hello"
end

it "canonicalizes the url without the path" do
Domainatrix::Url.new(:subdomain => "foo", :domain => "pauldix", :tld => "net").canonical(:include_path => false).should == "net.pauldix.foo"
end
end

0 comments on commit f80c552

Please sign in to comment.