module System
Maps individual URL path segments to and from local filesystem components.
Unlike generic URL decoding, this encoding rejects values which would turn one URL segment into multiple local path components.
Definitions
def self.escape(component)
Encode one local filesystem component as one URL path segment.
Signature
-
parameter
componentString The local filesystem component.
-
returns
String The encoded URL segment.
-
raises
ArgumentError If the component cannot be converted or contains a system path separator.
Implementation
def self.escape(component)
validate(component)
Encoding.escape(transcode(component, ::Encoding::UTF_8))
end
def self.unescape(segment)
Decode one URL path segment as one local filesystem component.
Signature
-
parameter
segmentString The encoded URL segment.
-
returns
String The local filesystem component.
-
raises
ArgumentError If the segment cannot map to one local filesystem component.
Implementation
def self.unescape(segment)
component = Encoding.unescape(segment, ::Encoding::UTF_8)
validate(component)
transcode(component, ENCODING)
end
def self.transcode(component, encoding)
Transcode a path component to the requested character encoding.
Implementation
def self.transcode(component, encoding)
component.encode(encoding)
rescue ::Encoding::InvalidByteSequenceError, ::Encoding::UndefinedConversionError
raise ArgumentError, "Path component could not be transcoded!"
end
def self.validate(component)
Validate that a string can represent exactly one local filesystem component.
Implementation
def self.validate(component)
unless component.valid_encoding?
raise ArgumentError, "Path component has invalid encoding!"
end
if INVALID_CHARACTER_PATTERN.match?(component)
raise ArgumentError, "Path component contains invalid characters!"
end
end