diff --git a/actionview/lib/action_view/template/handlers/erb.rb b/actionview/lib/action_view/template/handlers/erb.rb index 8341188af4..84cd7f669e 100644 --- a/actionview/lib/action_view/template/handlers/erb.rb +++ b/actionview/lib/action_view/template/handlers/erb.rb @@ -16,6 +16,9 @@ module ActionView # 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) @@ -45,6 +48,9 @@ module ActionView # 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 == "-") diff --git a/actionview/test/actionpack/abstract/abstract_controller_test.rb b/actionview/test/actionpack/abstract/abstract_controller_test.rb index 2de81596b5..c51b244ff3 100644 --- a/actionview/test/actionpack/abstract/abstract_controller_test.rb +++ b/actionview/test/actionpack/abstract/abstract_controller_test.rb @@ -52,6 +52,10 @@ module AbstractController 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 @@ -84,6 +88,14 @@ module AbstractController 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 diff --git a/actionview/test/actionpack/abstract/views/with_final_newline.erb b/actionview/test/actionpack/abstract/views/with_final_newline.erb new file mode 100644 index 0000000000..fe8b6dda71 --- /dev/null +++ b/actionview/test/actionpack/abstract/views/with_final_newline.erb @@ -0,0 +1 @@ +Hello from with_final_newline.erb