Skip to content

Instantly share code, notes, and snippets.

@ydnar
Created October 18, 2009 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ydnar/212744 to your computer and use it in GitHub Desktop.
Save ydnar/212744 to your computer and use it in GitHub Desktop.
Minimal safe ERb for Rails 2.3 — escapes all expressions by default
# Minimal Safe ERb for Rails 2.3
# Automatically HTML-escapes: <%= expr %>
# To pass raw text through: <%== expr %>
#
# Based on Erubis 2.6.5 and a bit of Rails 3:
# http://github.com/rails/rails/commit/9415935902f120a9bac0bfce7129725a0db38ed3
#
# To use, add this file to config/initializers and this line to environment.rb:
# config.gem "erubis", :version => "2.6.5"
require 'erubis'
module ActionView
module TemplateHandlers
class Erubis < ::Erubis::EscapedEruby
def add_preamble(src)
src << "@output_buffer = '';"
end
def add_text(src, text)
src << "@output_buffer << ('" << escape_text(text) << "');"
end
def add_expr_literal(src, code)
src << '@output_buffer << ((' << code << ').to_s);'
end
def add_expr_escaped(src, code)
src << '@output_buffer << ' << escaped_expr(code) << ';'
end
def add_postamble(src)
src << '@output_buffer.to_s'
end
end
class MinimalSafeERB < ERB
def compile(template)
magic = $1 if template.source =~ /\A(<%#.*coding[:=]\s*(\S+)\s*-?%>)/
erb = "#{magic}<% __in_erb_template=true %>#{template.source}"
Erubis.new(erb, :trim => (self.class.erb_trim_mode == "-")).src
end
end
Template.register_default_template_handler :erb, MinimalSafeERB
Template.register_template_handler :rhtml, MinimalSafeERB
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment