module HWSStrings # These constants are used as the default configuration for the # component_encode and component_decode methods. DEFAULT_ILLEGAL_CHARS = ['~', '/', ' '] DEFAULT_ESCAPE = '~' # Encode the string to make it usable as a single path in a URL. # # This a simple scheme that should allow you to match the string in a single # path variable easily, in a way that should not be messed with by your # web framework. # # Many characters that are legal as file names by the Helix Versioning Engine # can make URL handling difficult. The most basic is the forward slash '/'. # # This does *NOT* guarantee that the string is URL safe! You should still # percent-encode any string as a URL. def self.component_encode(str, illegal_characters: DEFAULT_ILLEGAL_CHARS) str.chars.map do |ch| if illegal_characters.include?(ch) '~' + ch.ord.to_s(16) else ch end end.join('') end # Decodes a string encoded with component_encode. def self.component_decode(str, escape = DEFAULT_ESCAPE, illegal_characters = DEFAULT_ILLEGAL_CHARS, base=16) escape_map = Hash[illegal_characters.map{ |c| [c, "#{escape}#{c.ord.to_s(base)}"] }] escape_map.each do |ch, escaped| str = str.gsub(escaped, ch) end str end end