class RDF::IRI
A Uniform Resource Identifier (URI). Also compatible with International Resource Identifier (IRI)
@example Creating a URI reference (1)
uri = RDF::URI.new("http://rubygems.org/gems/rdf")
@example Creating a URI reference (2)
uri = RDF::URI.new(scheme: 'http', host: 'rubygems.org', path: '/gems/rdf') #=> RDF::URI.new("http://rubygems.org/gems/rdf")
@example Creating an interned URI reference
uri = RDF::URI.intern("http://rubygems.org/gems/rdf")
@example Getting the string representation of a URI
uri.to_s #=> "http://rubygems.org/gems/rdf"
en.wikipedia.org/wiki/Internationalized_Resource_Identifier @see en.wikipedia.org/wiki/Uniform_Resource_Identifier @see www.ietf.org/rfc/rfc3986.txt @see www.ietf.org/rfc/rfc3987.txt @see addressable.rubyforge.org/
Constants
- CACHE_SIZE
Defines the maximum number of interned URI references that can be held cached in memory at any one time.
- GEN_DELIMS
- IAUTHORITY
- IFRAGMENT
- IHIER_PART
- IHOST
- IPATH_ABEMPTY
- IPATH_ABSOLUTE
- IPATH_EMPTY
- IPATH_NOSCHEME
- IPATH_ROOTLESS
- IPCHAR
- IPRIVATE
- IP_literal
- IQUERY
- IREG_NAME
- IRELATIVE_PART
- IRELATIVE_REF
- IRI
- IRI_PARTS
Split an IRI into it's component parts
- ISEGMENT
- ISEGMENT_NZ
- ISEGMENT_NZ_NC
- IUNRESERVED
- IUSERINFO
- NON_HIER_SCHEMES
List of schemes known not to be hierarchical
- PCT_ENCODED
- PORT
- PORT_MAPPING
Remove port, if it is standard for the scheme when normalizing
- RDS_2A
Remove dot expressions regular expressions
- RDS_2B1
- RDS_2B2
- RDS_2C1
- RDS_2C2
- RDS_2D
- RDS_2E
- RESERVED
- SCHEME
- SUB_DELIMS
- UCSCHAR
IRI components
- UNRESERVED
Public Class Methods
@return [RDF::Util::Cache] @private
# File lib/rdf/model/uri.rb, line 121 def self.cache require 'rdf/util/cache' unless defined?(::RDF::Util::Cache) @cache ||= RDF::Util::Cache.new(CACHE_SIZE) end
Returns an interned `RDF::URI` instance based on the given `uri` string.
The maximum number of cached interned URI references is given by the `CACHE_SIZE` constant. This value is unlimited by default, in which case an interned URI object will be purged only when the last strong reference to it is garbage collected (i.e., when its finalizer runs).
Excepting special memory-limited circumstances, it should always be safe and preferred to construct new URI references using `RDF::URI.intern` instead of `RDF::URI.new`, since if an interned object can't be returned for some reason, this method will fall back to returning a freshly-allocated one.
@param (see initialize) @return [RDF::URI] an immutable, frozen URI object
# File lib/rdf/model/uri.rb, line 143 def self.intern(*args) str = args.first (cache[(str = str.to_s).to_sym] ||= self.new(*args)).freeze end
@overload URI(uri, options = {})
@param [URI, String, #to_s] uri
@overload URI(options = {})
@param [Hash{Symbol => Object}] options @option [String, #to_s] :scheme The scheme component. @option [String, #to_s] :user The user component. @option [String, #to_s] :password The password component. @option [String, #to_s] :userinfo The userinfo component. If this is supplied, the user and password components must be omitted. @option [String, #to_s] :host The host component. @option [String, #to_s] :port The port component. @option [String, #to_s] :authority The authority component. If this is supplied, the user, password, userinfo, host, and port components must be omitted. @option [String, #to_s] :path The path component. @option [String, #to_s] :query The query component. @option [String, #to_s] :fragment The fragment component. @param [Boolean] validate (false) @param [Boolean] canonicalize (false)
# File lib/rdf/model/uri.rb, line 224 def initialize(*args, validate: false, canonicalize: false, **options) uri = args.first if uri @value = uri.to_s if @value.encoding != Encoding::UTF_8 @value = @value.dup if @value.frozen? @value.force_encoding(Encoding::UTF_8) @value.freeze end else %w( scheme user password userinfo host port authority path query fragment ).map(&:to_sym).each do |meth| if options.has_key?(meth) self.send("#{meth}=".to_sym, options[meth]) else self.send(meth) end end end validate! if validate canonicalize! if canonicalize end
Resolve paths to their simplest form.
@todo This process is correct, but overly iterative. It could be better done with a single regexp which handled most of the segment collapses all at once. Parent segments would still require iteration.
@param [String] path @return [String] normalized path @see tools.ietf.org/html/rfc3986#section-5.2.4
# File lib/rdf/model/uri.rb, line 169 def self.normalize_path(path) output, input = "", path.to_s if input.encoding != Encoding::ASCII_8BIT input = input.dup if input.frozen? input = input.force_encoding(Encoding::ASCII_8BIT) end until input.empty? if input.match(RDS_2A) # If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise, input = $1 elsif input.match(RDS_2B1) || input.match(RDS_2B2) # if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise, input = "/#{$1}" elsif input.match(RDS_2C1) || input.match(RDS_2C2) # if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer input = "/#{$1}" # and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise, output.sub!(/\/?[^\/]*$/, '') elsif input.match(RDS_2D) # if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise, input = "" elsif input.match(RDS_2E) # move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer.end seg, input = $1, $2 output << seg end end output.force_encoding(Encoding::UTF_8) end
Creates a new `RDF::URI` instance based on the given `uri` string.
This is just an alias for {RDF::URI#initialize} for compatibity with `Addressable::URI.parse`. Actual parsing is defered until {#object} is accessed.
@param [String, to_s] str @return [RDF::URI]
# File lib/rdf/model/uri.rb, line 157 def self.parse(str) self.new(str) end
Public Instance Methods
Simple concatenation operator. Returns a URI formed from concatenating the string form of two elements.
For building URIs from fragments, you may want to use the smart separator, `#/`. `#join` implements another set of URI building semantics.
@example Concatenating a string to a URI
RDF::URI.new('http://example.org/test') + 'test' #=> RDF::URI('http://example.org/testtest')
@example Concatenating two URIs
RDF::URI.new('http://example.org/test') + RDF::URI.new('test') #=> RDF::URI('http://example.org/testtest')
@see RDF::URI#/ @see #join @param [Any] other @return [RDF::URI]
# File lib/rdf/model/uri.rb, line 539 def +(other) RDF::URI.intern(self.to_s + other.to_s) end
'Smart separator' URI builder
This method attempts to use some understanding of the most common use cases for URLs and URNs to create a simple method for building new URIs from fragments. This means that it will always insert a separator of some sort, will remove duplicate seperators, will always assume that a fragment argument represents a relative and not absolute path, and throws an exception when an absolute URI is received for a fragment argument.
This is separate from the semantics for `#join`, which are well-defined by RFC3986 section 5.2 as part of the merging and normalization process; this method does not perform any normalization, removal of spurious paths, or removal of parent directory references `(/../)`.
See also `#+`, which concatenates the string forms of two URIs without any sort of checking or processing.
For an up-to-date list of edge case behavior, see the shared examples for RDF::URI in the rdf-spec project.
@param [Any] fragment A URI fragment to be appended to this URI @return [RDF::URI] @raise [ArgumentError] if the URI is invalid @see RDF::URI#+ @see #join @see <tools.ietf.org/html/rfc3986#section-5.2> @see <github.com/ruby-rdf/rdf-spec/blob/master/lib/rdf/spec/uri.rb> @example Building a HTTP URL
RDF::URI.new('http://example.org') / 'jhacker' / 'foaf.ttl' #=> RDF::URI('http://example.org/jhacker/foaf.ttl')
@example Building a HTTP URL (absolute path components)
RDF::URI.new('http://example.org/') / '/jhacker/' / '/foaf.ttl' #=> RDF::URI('http://example.org/jhacker/foaf.ttl')
@example Using an anchored base URI
RDF::URI.new('http://example.org/users#') / 'jhacker' #=> RDF::URI('http://example.org/users#jhacker')
@example Building a URN
RDF::URI.new('urn:isbn') / 125235111 #=> RDF::URI('urn:isbn:125235111')
# File lib/rdf/model/uri.rb, line 484 def /(fragment) frag = fragment.respond_to?(:to_uri) ? fragment.to_uri : RDF::URI(fragment.to_s) raise ArgumentError, "Non-absolute URI or string required, got #{frag}" unless frag.relative? if urn? RDF::URI.intern(to_s.sub(/:+$/,'') + ':' + fragment.to_s.sub(/^:+/,'')) else # !urn? res = self.dup if res.fragment case fragment.to_s[0,1] when '/' # Base with a fragment, fragment beginning with '/'. The fragment wins, we use '/'. path, frag = fragment.to_s.split('#', 2) res.path = "#{res.path}/#{path.sub(/^\/*/,'')}" res.fragment = frag else # Replace fragment res.fragment = fragment.to_s.sub(/^#+/,'') end else # Not a fragment. includes '/'. Results from bases ending in '/' are the same as if there were no trailing slash. case fragment.to_s[0,1] when '#' # Base ending with '/', fragment beginning with '#'. The fragment wins, we use '#'. res.path = res.path.to_s.sub!(/\/*$/, '') # Add fragment res.fragment = fragment.to_s.sub(/^#+/,'') else # Add fragment as path component path, frag = fragment.to_s.split('#', 2) res.path = res.path.to_s.sub(/\/*$/,'/') + path.sub(/^\/*/,'') res.fragment = frag end end RDF::URI.intern(res.to_s) end end
Checks whether this URI is equal to `other` (type checking).
Per SPARQL data-r2/expr-equal/eq-2-2, numeric can't be compared with other types
@example
RDF::URI('http://t.co/') == RDF::URI('http://t.co/') #=> true RDF::URI('http://t.co/') == 'http://t.co/' #=> true RDF::URI('http://www.w3.org/2000/01/rdf-schema#') == RDF::RDFS #=> true
@param [Object] other @return [Boolean] `true` or `false` @see www.w3.org/TR/rdf-sparql-query/#func-RDFterm-equal
# File lib/rdf/model/uri.rb, line 733 def ==(other) case other when Literal # If other is a Literal, reverse test to consolodate complex type checking logic other == self when String then to_s == other when URI then hash == other.hash && to_s == other.to_s else other.respond_to?(:to_uri) && to_s == other.to_uri.to_s end end
Checks for case equality to the given `other` object.
@example
RDF::URI('http://example.org/') === /example/ #=> true RDF::URI('http://example.org/') === /foobar/ #=> false RDF::URI('http://t.co/') === RDF::URI('http://t.co/') #=> true RDF::URI('http://t.co/') === 'http://t.co/' #=> true RDF::URI('http://www.w3.org/2000/01/rdf-schema#') === RDF::RDFS #=> true
@param [Object] other @return [Boolean] `true` or `false` @since 0.3.0
# File lib/rdf/model/uri.rb, line 757 def ===(other) case other when Regexp then other === to_s else self == other end end
Performs a pattern match using the given regular expression.
@example
RDF::URI('http://example.org/') =~ /example/ #=> 7 RDF::URI('http://example.org/') =~ /foobar/ #=> nil
@param [Regexp] pattern @return [Integer] the position the match starts @see String#=~ @since 0.3.0
# File lib/rdf/model/uri.rb, line 775 def =~(pattern) case pattern when Regexp then to_s =~ pattern else super # `Object#=~` returns `false` end end
A URI is absolute when it has a scheme @return [Boolean] `true` or `false`
# File lib/rdf/model/uri.rb, line 305 def absolute?; !scheme.nil?; end
Returns a copy of this URI converted into its canonical lexical representation.
@return [RDF::URI] @since 0.3.0
# File lib/rdf/model/uri.rb, line 365 def canonicalize self.dup.canonicalize! end
Converts this URI into its canonical lexical representation.
@return [RDF::URI] `self` @since 0.3.0
# File lib/rdf/model/uri.rb, line 375 def canonicalize! @object = { scheme: normalized_scheme, authority: normalized_authority, path: normalized_path.squeeze('/'), query: normalized_query, fragment: normalized_fragment } @value = nil self end
Returns a duplicate copy of `self`.
@return [RDF::URI]
# File lib/rdf/model/uri.rb, line 656 def dup self.class.new((@value || @object).dup) end
Returns `true` if this URI ends with the given `string`.
@example
RDF::URI('http://example.org/').end_with?('/') #=> true RDF::URI('http://example.org/').end_with?('#') #=> false
@param [String, to_s] string @return [Boolean] `true` or `false` @see String#end_with? @since 0.3.0
# File lib/rdf/model/uri.rb, line 701 def end_with?(string) to_s.end_with?(string.to_s) end
Checks whether this URI the same term as `other`.
@example
RDF::URI('http://t.co/').eql?(RDF::URI('http://t.co/')) #=> true RDF::URI('http://t.co/').eql?('http://t.co/') #=> false RDF::URI('http://www.w3.org/2000/01/rdf-schema#').eql?(RDF::RDFS) #=> false
@param [RDF::URI] other @return [Boolean] `true` or `false`
# File lib/rdf/model/uri.rb, line 716 def eql?(other) other.is_a?(URI) && self.hash == other.hash && self == other end
@return [String]
# File lib/rdf/model/uri.rb, line 1090 def fragment object.fetch(:fragment) do nil end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 1099 def fragment=(value) object[:fragment] = (value.to_s.force_encoding(Encoding::UTF_8) if value) @value = nil self end
@private
# File lib/rdf/model/uri.rb, line 662 def freeze unless frozen? # Create derived components authority; userinfo; user; password; host; port @value = value.freeze @object = object.freeze @hash = hash.freeze super end self end
Returns `true` if this URI is hierarchical and it's path component isn't equal to `/`.
@example
RDF::URI('http://example.org/').has_parent? #=> false RDF::URI('http://example.org/path/').has_parent? #=> true
@return [Boolean] `true` or `false`
# File lib/rdf/model/uri.rb, line 585 def has_parent? !root? end
Returns a hash code for this URI.
@return [Fixnum]
# File lib/rdf/model/uri.rb, line 825 def hash @hash ||= (value.hash * -1) end
Returns `true` if the URI scheme is hierarchical.
@example
RDF::URI('http://example.org/').hier? #=> true RDF::URI('urn:isbn:125235111').hier? #=> false
@return [Boolean] `true` or `false` @see en.wikipedia.org/wiki/URI_scheme @see {NON_HIER_SCHEMES} @since 1.0.10
# File lib/rdf/model/uri.rb, line 285 def hier? !NON_HIER_SCHEMES.include?(scheme) end
@return [String]
# File lib/rdf/model/uri.rb, line 946 def host object.fetch(:host) do @object[:host] = ($1 if @object[:authority].to_s.match(/(?:[^@]+@)?([^:]+)(?::.*)?$/)) end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 955 def host=(value) object[:host] = (value.to_s.force_encoding(Encoding::UTF_8) if value) @object[:authority] = format_authority @value = nil self end
Joins several URIs together.
This method conforms to join normalization semantics as per RFC3986, section 5.2. This method normalizes URIs, removes some duplicate path information, such as double slashes, and other behavior specified in the RFC.
Other URI building methods are `#/` and `#+`.
For an up-to-date list of edge case behavior, see the shared examples for RDF::URI in the rdf-spec project.
@example Joining two URIs
RDF::URI.new('http://example.org/foo/bar').join('/foo') #=> RDF::URI('http://example.org/foo')
@see <github.com/ruby-rdf/rdf-spec/blob/master/lib/rdf/spec/uri.rb> @see <tools.ietf.org/html/rfc3986#section-5.2> @see RDF::URI#/ @see RDF::URI#+ @param [Array<String, RDF::URI, to_s>] uris @return [RDF::URI] @see tools.ietf.org/html/rfc3986#section-5.2.2 @see tools.ietf.org/html/rfc3986#section-5.2.3
# File lib/rdf/model/uri.rb, line 412 def join(*uris) joined_parts = object.dup.delete_if {|k, v| [:user, :password, :host, :port].include?(k)} uris.each do |uri| uri = RDF::URI.new(uri) unless uri.is_a?(RDF::URI) next if uri.to_s.empty? # Don't mess with base URI case when uri.scheme joined_parts = uri.object.merge(path: self.class.normalize_path(uri.path)) when uri.authority joined_parts[:authority] = uri.authority joined_parts[:path] = self.class.normalize_path(uri.path) joined_parts[:query] = uri.query when uri.path.to_s.empty? joined_parts[:query] = uri.query if uri.query when uri.path[0,1] == '/' joined_parts[:path] = self.class.normalize_path(uri.path) joined_parts[:query] = uri.query else # Merge path segments from section 5.2.3 base_path = path.to_s.sub(/\/[^\/]*$/, '/') joined_parts[:path] = self.class.normalize_path(base_path + uri.path) joined_parts[:query] = uri.query end joined_parts[:fragment] = uri.fragment end # Return joined URI RDF::URI.new(joined_parts) end
Returns the string length of this URI.
@example
RDF::URI('http://example.org/').length #=> 19
@return [Integer] @since 0.3.0
# File lib/rdf/model/uri.rb, line 332 def length to_s.length end
Normalized version of fragment @return [String]
# File lib/rdf/model/uri.rb, line 1108 def normalized_fragment normalize_segment(fragment, IFRAGMENT) if fragment end
Normalized version of host @return [String]
# File lib/rdf/model/uri.rb, line 965 def normalized_host # Remove trailing '.' characters normalize_segment(host, IHOST, true).chomp('.') if host end
Normalized version of password @return [String]
# File lib/rdf/model/uri.rb, line 940 def normalized_password ::URI.encode(::URI.decode(password), /[^#{IUNRESERVED}|#{SUB_DELIMS}]/) if password end
Normalized version of path @return [String]
# File lib/rdf/model/uri.rb, line 1028 def normalized_path segments = path.to_s.split('/', -1) # preserve null segments norm_segs = case when authority # ipath-abempty segments.map {|s| normalize_segment(s, ISEGMENT)} when segments[0].nil? # ipath-absolute res = [nil] res << normalize_segment(segments[1], ISEGMENT_NZ) if segments.length > 1 res += segments[2..-1].map {|s| normalize_segment(s, ISEGMENT)} if segments.length > 2 res when segments[0].to_s.index(':') # ipath-noscheme res = [] res << normalize_segment(segments[0], ISEGMENT_NZ_NC) res += segments[1..-1].map {|s| normalize_segment(s, ISEGMENT)} if segments.length > 1 res when segments[0] # ipath-rootless # ipath-noscheme res = [] res << normalize_segment(segments[0], ISEGMENT_NZ) res += segments[1..-1].map {|s| normalize_segment(s, ISEGMENT)} if segments.length > 1 res else # Should be empty segments end res = self.class.normalize_path(norm_segs.join("/")) # Special rules for specific protocols having empty paths normalize_segment(res.empty? ? (%w(http https ftp tftp).include?(normalized_scheme) ? '/' : "") : res, IHIER_PART) end
Normalized version of port @return [String]
# File lib/rdf/model/uri.rb, line 991 def normalized_port if port np = normalize_segment(port.to_s, PORT) if PORT_MAPPING[normalized_scheme] == np.to_i nil else np.to_i end end end
Normalized version of query @return [String]
# File lib/rdf/model/uri.rb, line 1084 def normalized_query normalize_segment(query, IQUERY) if query end
Return normalized version of scheme, if any @return [String]
# File lib/rdf/model/uri.rb, line 888 def normalized_scheme normalize_segment(scheme.strip, SCHEME, true) if scheme end
Normalized version of user @return [String]
# File lib/rdf/model/uri.rb, line 914 def normalized_user ::URI.encode(::URI.decode(user), /[^#{IUNRESERVED}|#{SUB_DELIMS}]/) if user end
Normalized version of userinfo @return [String]
# File lib/rdf/model/uri.rb, line 1164 def normalized_userinfo normalized_user + (password ? ":#{normalized_password}" : "") if userinfo end
Returns object representation of this URI, broken into components
@return [Hash{Symbol => String}]
# File lib/rdf/model/uri.rb, line 833 def object @object ||= parse(@value) end
Returns a copy of this URI with the path component ascended to the parent directory, if any.
@example
RDF::URI('http://example.org/').parent #=> nil RDF::URI('http://example.org/path/').parent #=> RDF::URI('http://example.org/')
@return [RDF::URI]
# File lib/rdf/model/uri.rb, line 598 def parent case when root? then nil else require 'pathname' unless defined?(Pathname) if path = Pathname.new(self.path).parent uri = self.dup uri.path = path.to_s uri.path << '/' unless uri.root? uri end end end
{ Parse a URI into it's components
@param [String, #to_s] value @return [Object{Symbol => String}]
# File lib/rdf/model/uri.rb, line 843 def parse(value) value = value.to_s.dup.force_encoding(Encoding::ASCII_8BIT) parts = {} if matchdata = value.to_s.match(IRI_PARTS) scheme, authority, path, query, fragment = matchdata.to_a[1..-1] userinfo, hostport = authority.to_s.split('@', 2) hostport, userinfo = userinfo, nil unless hostport user, password = userinfo.to_s.split(':', 2) host, port = hostport.to_s.split(':', 2) parts[:scheme] = (scheme.force_encoding(Encoding::UTF_8) if scheme) parts[:authority] = (authority.force_encoding(Encoding::UTF_8) if authority) parts[:userinfo] = (userinfo.force_encoding(Encoding::UTF_8) if userinfo) parts[:user] = (user.force_encoding(Encoding::UTF_8) if user) parts[:password] = (password.force_encoding(Encoding::UTF_8) if password) parts[:host] = (host.force_encoding(Encoding::UTF_8) if host) parts[:port] = (::URI.decode(port).to_i if port) parts[:path] = (path.to_s.force_encoding(Encoding::UTF_8) unless path.empty?) parts[:query] = (query[1..-1].force_encoding(Encoding::UTF_8) if query) parts[:fragment] = (fragment[1..-1].force_encoding(Encoding::UTF_8) if fragment) end parts end
@return [String]
# File lib/rdf/model/uri.rb, line 920 def password object.fetch(:password) do @object[:password] = (userinfo.split(':', 2)[1] if userinfo) end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 929 def password=(value) object[:password] = (value.to_s.force_encoding(Encoding::UTF_8) if value) @object[:userinfo] = format_userinfo("") @object[:authority] = format_authority @value = nil self end
@return [String]
# File lib/rdf/model/uri.rb, line 1004 def path object.fetch(:path) do nil end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 1013 def path=(value) if value # Always lead with a slash value = "/#{value}" if host && value.to_s =~ /^[^\/]/ object[:path] = value.to_s.force_encoding(Encoding::UTF_8) else object[:path] = nil end @value = nil self end
Returns a string version of the QName or the full IRI
@return [String] or `nil`
# File lib/rdf/model/uri.rb, line 648 def pname (q = self.qname) ? q.join(":") : to_s end
@return [String]
# File lib/rdf/model/uri.rb, line 972 def port object.fetch(:port) do @object[:port] = ($1 if @object[:authority].to_s.match(/:(\d+)$/)) end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 981 def port=(value) object[:port] = (value.to_s.to_i if value) @object[:authority] = format_authority @value = nil self end
Returns a qualified name (QName) for this URI based on available vocabularies, if possible.
@example
RDF::URI('http://www.w3.org/2000/01/rdf-schema#').qname #=> [:rdfs, nil] RDF::URI('http://www.w3.org/2000/01/rdf-schema#label').qname #=> [:rdfs, :label] RDF::RDFS.label.qname #=> [:rdfs, :label]
@return [Array(Symbol, Symbol)] or `nil` if no QName found
# File lib/rdf/model/uri.rb, line 621 def qname if self.to_s =~ %r([:/#]([^:/#]*)$) local_name = $1 vocab_uri = local_name.empty? ? self.to_s : self.to_s[0...-(local_name.length)] Vocabulary.each do |vocab| if vocab.to_uri == vocab_uri prefix = vocab.equal?(RDF) ? :rdf : vocab.__prefix__ return [prefix, local_name.empty? ? nil : local_name.to_sym] end end else Vocabulary.each do |vocab| vocab_uri = vocab.to_uri if self.start_with?(vocab_uri) prefix = vocab.equal?(RDF) ? :rdf : vocab.__prefix__ local_name = self.to_s[vocab_uri.length..-1] return [prefix, local_name.empty? ? nil : local_name.to_sym] end end end return nil # no QName found end
@return [String]
# File lib/rdf/model/uri.rb, line 1066 def query object.fetch(:query) do nil end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 1075 def query=(value) object[:query] = (value.to_s.force_encoding(Encoding::UTF_8) if value) @value = nil self end
Converts the query component to a Hash value.
@example
RDF::URI.new("?one=1&two=2&three=3").query_values #=> {"one" => "1", "two" => "2", "three" => "3"} RDF::URI.new("?one=two&one=three").query_values(Array) #=> [["one", "two"], ["one", "three"]] RDF::URI.new("?one=two&one=three").query_values(Hash) #=> {"one" => ["two", "three"]}
@param [Class] return_type (Hash)
The return type desired. Value must be either # `Hash` or `Array`.
@return [Hash, Array] The query string parsed as a Hash or Array object.
# File lib/rdf/model/uri.rb, line 1182 def query_values(return_type=Hash) raise ArgumentError, "Invalid return type. Must be Hash or Array." unless [Hash, Array].include?(return_type) return nil if query.nil? query.to_s.split('&'). inject(return_type == Hash ? {} : []) do |memo,kv| k,v = kv.to_s.split('=', 2) next if k.to_s.empty? k = ::URI.decode(k) v = ::URI.decode(v) if v if return_type == Hash case memo[k] when nil then memo[k] = v when Array then memo[k] << v else memo[k] = [memo[k], v] end else memo << [k, v].compact end memo end end
Sets the query component for this URI from a Hash object. An empty Hash or Array will result in an empty query string.
@example Hash with single and array values
uri.query_values = {a: "a", b: ["c", "d", "e"]} uri.query # => "a=a&b=c&b=d&b=e"
@example Array with Array values including repeated variables
uri.query_values = [['a', 'a'], ['b', 'c'], ['b', 'd'], ['b', 'e']] uri.query # => "a=a&b=c&b=d&b=e"
@example Array with Array values including multiple elements
uri.query_values = [['a', 'a'], ['b', ['c', 'd', 'e']]] uri.query # => "a=a&b=c&b=d&b=e"
@example Array with Array values having only one entry
uri.query_values = [['flag'], ['key', 'value']] uri.query # => "flag&key=value"
@param [Hash, to_hash, Array] value The new query values.
# File lib/rdf/model/uri.rb, line 1229 def query_values=(value) if value.nil? self.query = nil return end value = value.to_hash if value.respond_to?(:to_hash) self.query = case value when Array, Hash value.map do |(k,v)| k = normalize_segment(k.to_s, UNRESERVED) if v.nil? k else Array(v).map do |vv| if vv === TrueClass k else "#{k}=#{normalize_segment(vv.to_s, UNRESERVED)}" end end.join("&") end end else raise TypeError, "Can't convert #{value.class} into Hash." end.join("&") end
A URI is relative when it does not have a scheme @return [Boolean] `true` or `false`
# File lib/rdf/model/uri.rb, line 310 def relative?; !absolute?; end
Attempt to make this URI relative to the provided `base_uri`. If successful, returns a relative URI, otherwise the original URI @param [#to_s] base_uri @return [RDF::URI]
# File lib/rdf/model/uri.rb, line 315 def relativize(base_uri) if base_uri.to_s.end_with?("/", "#") && self.to_s.start_with?(base_uri.to_s) RDF::URI(self.to_s[base_uri.to_s.length..-1]) else self end end
The HTTP request URI for this URI. This is the path and the query string.
@return [String] The request URI required for an HTTP request.
# File lib/rdf/model/uri.rb, line 1263 def request_uri return nil if absolute? && scheme !~ /^https?$/ res = path.to_s.empty? ? "/" : path res += "?#{self.query}" if self.query return res end
Returns a copy of this URI with the path component set to `/`.
@example
RDF::URI('http://example.org/').root #=> RDF::URI('http://example.org/') RDF::URI('http://example.org/path/').root #=> RDF::URI('http://example.org/')
@return [RDF::URI]
# File lib/rdf/model/uri.rb, line 567 def root if root? self else RDF::URI.new( object.merge(path: '/'). keep_if {|k, v| [:scheme, :authority, :path].include?(k)}) end end
Returns `true` if this URI's scheme is not hierarchical, or its path component is equal to `/`. Protocols not using hierarchical components are always considered to be at the root.
@example
RDF::URI('http://example.org/').root? #=> true RDF::URI('http://example.org/path/').root? #=> false RDF::URI('urn:isbn').root? #=> true
@return [Boolean] `true` or `false`
# File lib/rdf/model/uri.rb, line 555 def root? !self.hier? || self.path == '/' || self.path.to_s.empty? end
@return [String]
# File lib/rdf/model/uri.rb, line 870 def scheme object.fetch(:scheme) do nil end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 879 def scheme=(value) object[:scheme] = (value.to_s.force_encoding(Encoding::UTF_8) if value) @value = nil self end
Returns `true` if this URI starts with the given `string`.
@example
RDF::URI('http://example.org/').start_with?('http') #=> true RDF::URI('http://example.org/').start_with?('ftp') #=> false
@param [String, to_s] string @return [Boolean] `true` or `false` @see String#start_with? @since 0.3.0
# File lib/rdf/model/uri.rb, line 685 def start_with?(string) to_s.start_with?(string.to_s) end
Returns the string representation of this URI.
@example
RDF::URI('http://example.org/').to_str #=> 'http://example.org/'
@return [String]
# File lib/rdf/model/uri.rb, line 797 def to_str; value; end
Returns `self`.
@return [RDF::URI] `self`
# File lib/rdf/model/uri.rb, line 786 def to_uri self end
Returns `true`.
@return [Boolean] `true` or `false` @see en.wikipedia.org/wiki/Uniform_Resource_Identifier
# File lib/rdf/model/uri.rb, line 257 def uri? true end
Returns `true` if this URI is a URL.
@example
RDF::URI('http://example.org/').url? #=> true
@return [Boolean] `true` or `false` @see en.wikipedia.org/wiki/Uniform_Resource_Locator @since 0.2.0
# File lib/rdf/model/uri.rb, line 298 def url? !urn? end
Returns `true` if this URI is a URN.
@example
RDF::URI('http://example.org/').urn? #=> false
@return [Boolean] `true` or `false` @see en.wikipedia.org/wiki/Uniform_Resource_Name @since 0.2.0
# File lib/rdf/model/uri.rb, line 270 def urn? @object ? @object[:scheme] == 'urn' : start_with?('urn:') end
@return [String]
# File lib/rdf/model/uri.rb, line 894 def user object.fetch(:user) do @object[:user] = (userinfo.split(':', 2)[0] if userinfo) end end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 903 def user=(value) object[:user] = (value.to_s.force_encoding(Encoding::UTF_8) if value) @object[:userinfo] = format_userinfo("") @object[:authority] = format_authority @value = nil self end
Userinfo is a combination of user and password
# File lib/rdf/model/uri.rb, line 1144 def userinfo object.fetch(:userinfo) { @object[:userinfo] = (format_userinfo("") if @object[:user]) } end
@param [String, to_s] value @return [RDF::URI] self
# File lib/rdf/model/uri.rb, line 1153 def userinfo=(value) object.delete_if {|k, v| [:user, :password, :authority].include?(k)} object[:userinfo] = (value.to_s.force_encoding(Encoding::UTF_8) if value) user; password; authority @value = nil self end
Determine if the URI is a valid according to RFC3987
Note that RDF URIs syntactically can contain Unicode escapes, which are unencoded in the internal representation. To validate, %-encode specifically excluded characters from IRIREF
@return [Boolean] `true` or `false` @since 0.3.9
# File lib/rdf/model/uri.rb, line 344 def valid? to_s.match(RDF::URI::IRI) || false end
lexical representation of URI, either absolute or relative @return [String]
# File lib/rdf/model/uri.rb, line 811 def value @value ||= [ ("#{scheme}:" if absolute?), ("//#{authority}" if authority), path, ("?#{query}" if query), ("##{fragment}" if fragment) ].compact.join("").freeze end
Private Instance Methods
# File lib/rdf/model/uri.rb, line 1289 def format_userinfo(append = "") if @object[:user] @object[:user] + (@object[:password] ? ":#{@object[:password]}" : "") + append else "" end end
Normalize a segment using a character range
@param [String] value @param [Regexp] expr @param [Boolean] downcase @return [String]
# File lib/rdf/model/uri.rb, line 1279 def normalize_segment(value, expr, downcase = false) if value value = value.dup if value.frozen? value = value.force_encoding(Encoding::UTF_8) decoded = ::URI.decode(value) decoded.downcase! if downcase ::URI.encode(decoded, /[^(?:#{expr})]/) end end