Class: Bridgetown::FrontMatter::Loaders::Ruby

Inherits:
Base
  • Object
show all
Defined in:
lib/bridgetown-core/front_matter/loaders/ruby.rb

Overview

Reads Ruby front matter delineated by fenced code blocks or ERB/Serbea indicators.

For example, all of these resources load the hash {published: false, title: "My post"} as their front matter.

```ruby
{
  published: false,
  title: My post
}
```
~~~ruby
{
  published: false,
  title: My post
}
~~~
###ruby
{
  published: false,
  title: My post
}
###
---ruby
{
  published: false,
  title: My post
}
---
~~~<%
{
  published: false,
  title: My post
}
%>~~~
~~~{%
{
  published: false,
  title: My post
}
%}~~~

Constant Summary collapse

HEADER =
%r!\A[~`#-]{3,}(?:ruby|<%|{%)[ \t]*\n!
BLOCK =
%r!#{HEADER.source}(.*?\n?)^((?:%>|%})?[~`#-]{3,}[ \t]*$\n?)!m

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from Bridgetown::FrontMatter::Loaders::Base

Class Method Details

.header?(file) ⇒ Boolean

Determines whether a given file has Ruby front matter

Parameters:

  • file (Pathname, String)

    the path to the file

Returns:

  • (Boolean)

    true if the file has Ruby front matter, false otherwise



72
73
74
# File 'lib/bridgetown-core/front_matter/loaders/ruby.rb', line 72

def self.header?(file)
  File.open(file, "rb", &:gets)&.match?(HEADER) || false
end

Instance Method Details

#read(file_contents, file_path:) ⇒ Object

See Also:

  • Bridgetown::FrontMatter::Loaders::Ruby.{Base{Base#read}


77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/bridgetown-core/front_matter/loaders/ruby.rb', line 77

def read(file_contents, file_path:)
  if (ruby_content = file_contents.match(BLOCK)) && should_execute_inline_ruby?
    Result.new(
      content: ruby_content.post_match.lstrip,
      front_matter: process_ruby_data(ruby_content[1], file_path, 2),
      line_count: ruby_content[1].lines.size - 1
    )
  elsif self.class.header?(file_path)
    Result.new(
      front_matter: process_ruby_data(
        File.read(file_path).lines[1..].join("\n"),
        file_path,
        2
      ),
      line_count: 0
    )
  end
end