From 72d613e68aef80b79b10fa6b9b8db808944816f2 Mon Sep 17 00:00:00 2001 From: Ito Date: Mon, 14 Nov 2022 04:37:52 +0200 Subject: [PATCH] Prevent the transformation of multiline do-end blocks to single-line blocks with curly braces by syntax_tree --- lib/erb/formatter.rb | 10 +++++++--- test/fixtures/short-do-end-block.html.erb | 3 +++ test/fixtures/short-do-end-block.html.expected.erb | 3 +++ 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 test/fixtures/short-do-end-block.html.erb create mode 100644 test/fixtures/short-do-end-block.html.expected.erb diff --git a/lib/erb/formatter.rb b/lib/erb/formatter.rb index 76459e9..27df1cb 100644 --- a/lib/erb/formatter.rb +++ b/lib/erb/formatter.rb @@ -213,8 +213,12 @@ def format_text(text) def format_ruby(code, autoclose: false, extra_indent: 0) if autoclose - code += "\nend" unless RUBY_OPEN_BLOCK["#{code}\nend"] - code += "\n}" unless RUBY_OPEN_BLOCK["#{code}\n}"] + # A long placeholder is added to prevent the transformation of + # multiline do-end blocks to single-line blocks with curly braces by syntax_tree. + placeholder = "placeholder_#{SecureRandom.hex(@line_width / 2)}" + + code += "\n#{placeholder}\nend" unless RUBY_OPEN_BLOCK["#{code}\nend"] + code += "\n#{placeholder}\n}" unless RUBY_OPEN_BLOCK["#{code}\n}"] end p RUBY_IN_: code if @debug @@ -229,8 +233,8 @@ def format_ruby(code, autoclose: false, extra_indent: 0) code end + code = code.split(placeholder).first.rstrip if autoclose lines = code.lines(chomp: true) - lines.delete_at(-1) if autoclose indent = "\s" * extra_indent diff --git a/test/fixtures/short-do-end-block.html.erb b/test/fixtures/short-do-end-block.html.erb new file mode 100644 index 0000000..c1df53f --- /dev/null +++ b/test/fixtures/short-do-end-block.html.erb @@ -0,0 +1,3 @@ +<% [1, 2, 3].each do |i| %> + <%= i %> +<% end %> diff --git a/test/fixtures/short-do-end-block.html.expected.erb b/test/fixtures/short-do-end-block.html.expected.erb new file mode 100644 index 0000000..c1df53f --- /dev/null +++ b/test/fixtures/short-do-end-block.html.expected.erb @@ -0,0 +1,3 @@ +<% [1, 2, 3].each do |i| %> + <%= i %> +<% end %>