Module: OsCtl::Lib::StringEscape

Defined in:
lib/libosctl/string_escape.rb

Class Method Summary collapse

Class Method Details

.escape_path(path) ⇒ String

Escape path so that it can be used as a file name

Alphanumeric characters and “;” “:” are kept as is, while all other characters are replaced by C-style escape sequences.

Parameters:

  • path (String)

Returns:

  • (String)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/libosctl/string_escape.rb', line 10

def self.escape_path(path)
  path = path[1..] while path.start_with?('/')
  path = '/' if path.empty?

  path.each_char.inject('') do |ret, c|
    if c == '/'
      ret << '-'
    elsif /[a-zA-Z0-9:_]/ =~ c
      ret << c
    else
      ret << '\\x' << c.ord.to_s(16)
    end

    ret
  end
end

.unescape_path(str) ⇒ String

Return unescaped path as escaped by escape_path

Parameters:

  • str (String)

Returns:

  • (String)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/libosctl/string_escape.rb', line 30

def self.unescape_path(str)
  ret = '/'
  return ret if str == '-'

  escape_seq = nil

  ret << str.each_char.inject('') do |acc, c|
    if c == '\\'
      acc << escape_seq if escape_seq
      escape_seq = c

    elsif escape_seq
      escape_seq << c

      if escape_seq.length == 4 # \\ x <n> <n>
        acc << escape_seq[2..3].to_i(16).chr
        escape_seq = nil
      end

    elsif c == '-'
      acc << '/'

    else
      acc << c
    end

    acc
  end

  ret << escape_seq if escape_seq
  ret
end