Skip to content

Instantly share code, notes, and snippets.

@cGuille
Created March 10, 2014 21:49
Show Gist options
  • Select an option

  • Save cGuille/9475168 to your computer and use it in GitHub Desktop.

Select an option

Save cGuille/9475168 to your computer and use it in GitHub Desktop.
StringEscaper: a Ruby class designed to escape literal strings
#!/usr/bin/env ruby
BACKSLASH = '\\'
class StringEscaper
def initialize chars_to_escape, escaper = BACKSLASH
# The escaper char must be escaped as well:
chars_to_escape.push(escaper) unless chars_to_escape.include?(escaper)
# We escape backslashes as they are the regex escape character:
regex_content = chars_to_escape.join('|').gsub! '\\', '\\\\\\'
@regex = /(#{regex_content})/
@escaper = escaper
end
def escape value
return value.gsub(@regex) { |match| "#{@escaper}#{match}" }
end
end
# Sample usage:
escaper = StringEscaper.new ['"']
text = 'This is a "test"! /!\\'
puts "UNESCAPED TEXT: #{text}"
puts "ESCAPED TEXT : #{escaper.escape(text)}"
puts
puts '// Example, desclaring a JS var using the string above:'
puts '// Before:', "var str = \"#{text}\""
puts '// After: ', "var str = \"#{escaper.escape text}\""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment