jxson
8/12/2010 - 12:07 AM

javascript-escape.rb

# borrowed from rails actionpack/lib/action_view/helpers/javascript_helper.rb
JS_ESCAPE_MAP = {
  '\\'    => '\\\\',
  '</'    => '<\/',
  "\r\n"  => '\n',
  "\n"    => '\n',
  "\r"    => '\n',
  '"'     => '\\"',
  "'"     => "\\'" }

# Escape carrier returns and single and double quotes for JavaScript segments.
def escape_javascript(javascript)
  if javascript
    javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { JS_ESCAPE_MAP[$1] }
  else
    ''
  end
end

content = File.new('vendor/client-core/templates/login.mustache').read

File.open('test.js', 'w') {|f| f.write('var = "#{ escape_javascript(content)) }";' }