Shell Escaping in Ruby

Ruby's shell escaping quality can sometimes be bad, here how to fix it.

module Utils
  def self.escape(str)
    str = str.gsub(/(\\?[^A-Za-z0-9_\-.,:\/@\n])/) do
      if !$1.start_with?("\\")
        "\\#{$1}" else $1
      end
    end

    str.gsub(/\n/, "'\n'")
  end
end
Utils.escape(Utils.escape("hello\\ world"))
# => "hello\\ world"