Created
March 10, 2014 21:49
-
-
Save cGuille/9475168 to your computer and use it in GitHub Desktop.
StringEscaper: a Ruby class designed to escape literal strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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