lib/protocol/http/reference.rb in protocol-http-0.3.0 vs lib/protocol/http/reference.rb in protocol-http-0.4.0
- old
+ new
@@ -1,5 +1,7 @@
+# frozen_string_literal: true
+#
# Copyright, 2018, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
@@ -22,45 +24,66 @@
module Protocol
module HTTP
# A relative reference, excluding any authority.
class Reference
+ include Comparable
+
# Generate a reference from a path and user parameters. The path may contain a `#fragment` or `?query=parameters`.
def self.parse(path = '/', parameters = nil)
base, fragment = path.split('#', 2)
path, query_string = base.split('?', 2)
self.new(path, query_string, fragment, parameters)
end
- def initialize(path, query_string = nil, fragment = nil, parameters = nil)
+ def initialize(path = '/', query_string = nil, fragment = nil, parameters = nil)
@path = path
@query_string = query_string
@fragment = fragment
@parameters = parameters
end
- def self.[] reference
- if reference.is_a? self
- return reference
- else
- return self.parse(reference)
- end
- end
-
# The path component, e.g. /foo/bar/index.html
- attr :path
+ attr_accessor :path
# The un-parsed query string, e.g. 'x=10&y=20'
- attr :query_string
+ attr_accessor :query_string
# A fragment, the part after the '#'
- attr :fragment
+ attr_accessor :fragment
# User supplied parameters that will be appended to the query part.
- attr :parameters
+ attr_accessor :parameters
+ def freeze
+ return self if frozen?
+
+ @path.freeze
+ @query_string.freeze
+ @fragment.freeze
+ @parameters.freeze
+
+ super
+ end
+
+ def to_ary
+ [@path, @query_string, @fragment, @parameters]
+ end
+
+ def <=> other
+ to_ary <=> other.to_ary
+ end
+
+ def self.[] reference
+ if reference.is_a? self
+ return reference
+ else
+ return self.parse(reference)
+ end
+ end
+
def parameters?
@parameters and !@parameters.empty?
end
def query_string?
@@ -102,16 +125,12 @@
other.fragment,
other.parameters,
)
end
- def [] parameters
- self.dup(nil, parameters)
- end
-
def dup(path = nil, parameters = nil, merge = true)
- if @parameters and merge
+ if merge and @parameters
if parameters
parameters = @parameters.merge(parameters)
else
parameters = @parameters
end
@@ -130,10 +149,12 @@
def expand_path(base, relative)
if relative.start_with? '/'
return relative
else
- path = base.split('/')
+ path = base.split('/', -1)
+ path.pop
+
parts = relative.split('/')
parts.each do |part|
if part == '..'
path.pop