Skip to content

Commit

Permalink
Add option to strip trailing newlines from ERB templates
Browse files Browse the repository at this point in the history
Add failing test for views with trailing newlines

Add and test config option

Move config option to config/application.rb

Move implementation to ERB template handler

Move config option to ActionView::Template::Handlers::ERB
  • Loading branch information
boardfish committed Jun 4, 2021
1 parent 346ae79 commit fe5ef42
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions actionview/lib/action_view/template/handlers/erb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ class ERB
# Do not escape templates of these mime types.
class_attribute :escape_ignore_list, default: ["text/plain"]

# Strip trailing newlines from rendered output
class_attribute :strip_trailing_newlines, default: false

ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")

def self.call(template, source)
Expand Down Expand Up @@ -45,6 +48,9 @@ def call(template, source)
# Always make sure we return a String in the default_internal
erb.encode!

# Strip trailing newlines from the template if enabled
erb.chomp! if strip_trailing_newlines

options = {
escape: (self.class.escape_ignore_list.include? template.type),
trim: (self.class.erb_trim_mode == "-")
Expand Down
12 changes: 12 additions & 0 deletions actionview/test/actionpack/abstract/abstract_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ def index
render "index.erb"
end

def with_final_newline
render "with_final_newline.erb"
end

def index_to_string
self.response_body = render_to_string "index"
end
Expand Down Expand Up @@ -84,6 +88,14 @@ def setup
assert_equal "Hello from index.erb", @controller.response_body
end

test "stripping final newline works" do
ActionView::Template::Handlers::ERB.strip_trailing_newlines = true
@controller.process(:with_final_newline)
assert_equal "Hello from with_final_newline.erb", @controller.response_body
ensure
ActionView::Template::Handlers::ERB.strip_trailing_newlines = false
end

test "render_to_string works with a String as an argument" do
@controller.process(:index_to_string)
assert_equal "Hello from index.erb", @controller.response_body
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello from with_final_newline.erb

0 comments on commit fe5ef42

Please sign in to comment.