Module: Alt::URI::Escape

Defined in:
lib/rio/alturi/escape.rb

Constant Summary collapse

CHAR_TABLE =
{
  :path =>      build_escape_table(REGEXP::PCHAR),
  :query =>     build_escape_table(REGEXP::QCHAR),
  :query_part =>     build_escape_table(REGEXP::QPCHAR),
  :fragment =>  build_escape_table(REGEXP::FCHAR),
  :userinfo =>  build_escape_table(REGEXP::UCHAR),
  :user =>  build_escape_table(REGEXP::USERCHAR),
  :host =>  build_escape_table(REGEXP::HCHAR),
}
UNESCAPE_HASH =
build_unescape_hash

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build_escape_table(re) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/rio/alturi/escape.rb', line 6

def self.build_escape_table(re)
  ca = []

  (0..255).each do |n|
    ca[n] = (n.chr =~ re ? n.chr : sprintf('%%%02X', n))
  end
  return ca
end

.build_unescape_hashObject



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rio/alturi/escape.rb', line 38

def self.build_unescape_hash
  lookup = {}

  chars = "0123456789ABCDEF"
  chars.split('').each do |cu|
    chars.split('').each do |cl|
      str = "%#{cu}#{cl}"
      lookup[str] = str[1,2].hex.chr
    end
  end
  lookup
end

.escape(str, arg) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/rio/alturi/escape.rb', line 29

def self.escape(str,arg)
  tmp = ""
  table = (::Symbol === arg ? CHAR_TABLE[arg] : arg)
  str.each_byte do |b|
    tmp << table[b]
  end
  tmp.encode(str.encoding)
end

.unescape(estr) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/rio/alturi/escape.rb', line 52

def self.unescape(estr)
  ustr = ""
  pos = 0
  while npos = estr.index('%',pos)
    uh = UNESCAPE_HASH[estr[npos,3].upcase]
    ustr << estr[pos,npos-pos] << uh
    pos = npos +3
  end
  ustr << estr[pos..-1]
end

.unescape0(str, escaped = REGEXP::PCT_ENCODED) ⇒ Object



67
68
69
70
71
# File 'lib/rio/alturi/escape.rb', line 67

def self.unescape0(str, escaped = REGEXP::PCT_ENCODED)
  str.gsub(escaped) {
    [$&[1, 2].hex].pack('C')
  }.force_encoding(str.encoding)
end

Instance Method Details

#escape(str, arg) ⇒ Object



25
26
27
# File 'lib/rio/alturi/escape.rb', line 25

def escape(str,arg)
  Escape.escape(str,arg)
end

#unescape(str) ⇒ Object



63
64
65
# File 'lib/rio/alturi/escape.rb', line 63

def unescape(str)
  Escape.unescape(str)
end