Module: Extras::Shell

Defined in:
lib/extras/shell.rb

Instance Method Summary collapse

Instance Method Details

#escape(str, original: false) ⇒ Object Also known as: shellescape


rubocop:disable Metrics/CyclomaticComplexity Escapes a string double checking if it will double escape. rubocop:disable Metrics/PerceivedComplexity Note: This is taken from Ruby 2.3 StdLib.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/extras/shell.rb', line 19

def escape(str, original: false)
  if original
    return super(
      str
    )
  end

  if !str || str.empty? || str == '""' || str == "''"
    return '""'

  elsif str.is_a?(Array)
    str.map do |v|
      escape(v)
    end

  elsif str.is_a?(Hash)
    str.each do |k, v|
      str[k] = escape(
        v
      )
    end

  else
    regexp = /((?:\\)?[^A-Za-z0-9_\-.,:\/@\n])/
    str = str.gsub(regexp) { $1.start_with?("\\") ? $1 : "\\#{$1}" }
    str = str.gsub(/\n/, "'\n'")
    str
  end
end