Module: URI::Escape

Includes:
REGEXP
Included in:
URI
Defined in:
lib/uri/common.rb

Constant Summary

Constants included from REGEXP

REGEXP::ABS_PATH, REGEXP::ABS_URI, REGEXP::ABS_URI_REF, REGEXP::ESCAPED, REGEXP::FRAGMENT, REGEXP::HOST, REGEXP::OPAQUE, REGEXP::PORT, REGEXP::QUERY, REGEXP::REGISTRY, REGEXP::REL_PATH, REGEXP::REL_URI, REGEXP::REL_URI_REF, REGEXP::SCHEME, REGEXP::UNSAFE, REGEXP::URI_REF, REGEXP::USERINFO

Instance Method Summary collapse

Instance Method Details

#escape(str, unsafe = UNSAFE) ⇒ Object Also known as: encode

Synopsis

URI.escape(str [, unsafe])

Args

str

String to replaces in.

unsafe

Regexp that matches all symbols that must be replaced with codes. By default uses REGEXP::UNSAFE. When this argument is a String, it represents a character set.

Description

Escapes the string, replacing all unsafe characters with codes.

Usage

require 'uri'

enc_uri = URI.escape("http://example.com/?a=\11\15")
p enc_uri
# => "http://example.com/?a=%09%0D"

p URI.unescape(enc_uri)
# => "http://example.com/?a=\t\r"

p URI.escape("@?@!", "!?")
# => "@%3F@%21"


284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/uri/common.rb', line 284

def escape(str, unsafe = UNSAFE)
  unless unsafe.kind_of?(Regexp)
    # perhaps unsafe is String object
    unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false, 'N')
  end
  str.gsub(unsafe) do |us|
    tmp = ''
    us.each_byte do |uc|
      tmp << sprintf('%%%02X', uc)
    end
    tmp
  end
end

#unescape(str) ⇒ Object Also known as: decode

Synopsis

URI.unescape(str)

Args

str

Unescapes the string.

Usage

require 'uri'

enc_uri = URI.escape("http://example.com/?a=\11\15")
p enc_uri
# => "http://example.com/?a=%09%0D"

p URI.unescape(enc_uri)
# => "http://example.com/?a=\t\r"


319
320
321
322
323
# File 'lib/uri/common.rb', line 319

def unescape(str)
  str.gsub(ESCAPED) do
    $&[1,2].hex.chr
  end
end