Last active
March 14, 2017 10:23
-
-
Save joneslm1/c18eb1235f63df3220543907b92e3e51 to your computer and use it in GitHub Desktop.
URL Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UrlParser | |
attr_accessor :website, :parsed, :scheme, :domain, :port, :path, :query_string, :fragment_id | |
def initialize(website) | |
@website = website | |
end | |
def scheme | |
scheme = @website.partition(':') | |
scheme[0] | |
end | |
def domain | |
domain = @website.partition("//") | |
if domain[2].include?(':') | |
domain1 = domain[2].partition(":") | |
domain1[0] | |
else | |
domain1 = domain[2].partition("/") | |
domain1[0] | |
end | |
end | |
def port | |
port = (@website.partition(":"))[2] | |
if port.include?(":") | |
port1 = port.partition(":") | |
port2 = port1[2].partition('/') | |
port2[0] | |
elsif self.scheme == "http" | |
"80" | |
elsif self.scheme == "https" | |
"443" | |
end | |
end | |
def path | |
path = @website.partition("//") | |
path1 = path[2].partition('/') | |
if path1[2].include?('?') | |
path2 = (path1[2].partition('?')) | |
path3 = path2[0] | |
else | |
path3 = path1[2] | |
end | |
if path3.include?('#') | |
path4 = (path3[2].partition('#')) | |
else path4 = path3 | |
end | |
unless path4 == "" | |
path4 | |
else nil | |
end | |
end | |
def query_string | |
query_hash=[] | |
query = (@website.partition('?'))[2] | |
if query.include?('#') | |
query1 = (query.partition('#'))[0] | |
else query1 = query | |
end | |
if query1.include?('&') | |
query1 <<'&' | |
while query1.include?('&') | |
que = query1.partition('&') | |
query_hash << que[0] | |
query1=que[2] | |
end | |
query_hash.each { |x| x.gsub!("=", ",")} | |
query_hash= query_hash.map { |x| []<<x} | |
query_hash = query_hash.map {|x| x[0].split(",")} | |
query_hash.uniq.to_h | |
else | |
query2 = query1.partition('=') | |
query2.delete_at(1) | |
puts ([]<<query2).to_h | |
end | |
end | |
def fragment_id | |
(@website.partition("#"))[2] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment