Created
October 18, 2009 16:49
-
-
Save ydnar/212744 to your computer and use it in GitHub Desktop.
Minimal safe ERb for Rails 2.3 — escapes all expressions by default
This file contains 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
# 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