From 56b0ae25f226aafee37a76bd94cc0259bd77a719 Mon Sep 17 00:00:00 2001 From: Elia Schito Date: Tue, 17 Jan 2023 13:22:11 +0100 Subject: [PATCH] Add support for "---" front matter --- lib/erb/formatter.rb | 10 +++++++++- test/fixtures/front-matter.html.erb | 19 +++++++++++++++++++ test/fixtures/front-matter.html.expected.erb | 20 ++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/front-matter.html.erb create mode 100644 test/fixtures/front-matter.html.expected.erb diff --git a/lib/erb/formatter.rb b/lib/erb/formatter.rb index 9e07665..49f3cfb 100644 --- a/lib/erb/formatter.rb +++ b/lib/erb/formatter.rb @@ -78,7 +78,7 @@ def initialize(source, line_width: 80, filename: nil, debug: $DEBUG) @original_source = source @filename = filename || '(erb)' @line_width = line_width - @source = source.dup + @source = remove_front_matter source.dup @html = +"" @debug = debug @@ -103,6 +103,13 @@ def initialize(source, line_width: 80, filename: nil, debug: $DEBUG) freeze end + def remove_front_matter(source) + source.sub(/\A---\n[\s\S]*?\n---\n/) do |match| + @front_matter = match + match.gsub(/[^\n]/, ' ') + end + end + attr_accessor \ :source, :html, :tag_stack, :pre_pos, :pre_placeholders, :erb_tags, :erb_tags_regexp, :pre_placeholders_regexp, :tags_regexp, :line_width @@ -368,6 +375,7 @@ def format html.gsub!(erb_tags_regexp, erb_tags) html.gsub!(pre_placeholders_regexp, pre_placeholders) html.strip! + html.prepend @front_matter + "\n" if @front_matter html << "\n" end end diff --git a/test/fixtures/front-matter.html.erb b/test/fixtures/front-matter.html.erb new file mode 100644 index 0000000..a34b048 --- /dev/null +++ b/test/fixtures/front-matter.html.erb @@ -0,0 +1,19 @@ +--- +foo: :bar +bar: "BAZ" +Baz: | + foobar + foo-bar + foo bar +--- + +<% flash.each do |type, data| %> +<%= render AlertComponent.new(type: type, data: data) %> +<% end %> + +<%= render NavbarComponent.new %> + +
+<%= yield %> +
+ diff --git a/test/fixtures/front-matter.html.expected.erb b/test/fixtures/front-matter.html.expected.erb new file mode 100644 index 0000000..3400f12 --- /dev/null +++ b/test/fixtures/front-matter.html.expected.erb @@ -0,0 +1,20 @@ +--- +foo: :bar +bar: "BAZ" +Baz: | + foobar + foo-bar + foo bar +--- + + + <% flash.each do |type, data| %> + <%= render AlertComponent.new(type: type, data: data) %> + <% end %> + + <%= render NavbarComponent.new %> + +
+ <%= yield %> +
+