ydnar (owner)

Revisions

gist: 212744 Download_button fork
public
Description:
Minimal safe ERb for Rails 2.3 — escapes all expressions by default
Public Clone URL: git://gist.github.com/212744.git
Embed All Files: show embed
minimal_safe_erb.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 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