-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
require 'yaml' | ||
|
||
class Obsidian::MarkdownParser::FrontMatterParser | ||
# Look for frontmatter delimited by '---' lines | ||
# and try to interpret it as yaml. | ||
# If it is valid YAML, then denotes properties. | ||
# https://help.obsidian.md/Editing+and+formatting/Properties#Property+format | ||
def parse(content) | ||
enumerator = content.each_line | ||
first_line = enumerator.next | ||
|
||
if first_line.chomp != "---" | ||
return {} | ||
end | ||
|
||
lines = [] | ||
while true | ||
line = enumerator.next | ||
break if line.chomp == "---" | ||
lines << line | ||
end | ||
|
||
YAML.safe_load(lines.join) | ||
rescue YAML::SyntaxError, StopIteration => ex | ||
{} | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# frozen_string_literal: true | ||
|
||
RSpec.describe(Obsidian::MarkdownParser::FrontMatterParser) do | ||
subject(:parser) { described_class.new } | ||
it "parses valid yaml" do | ||
content = %(--- | ||
foo: 1 | ||
bar: banana | ||
--- | ||
some text | ||
) | ||
expect(parser.parse(content)).to eq({"foo" => 1, "bar" => "banana"}) | ||
end | ||
|
||
it "returns empty hash for invalid yaml" do | ||
content = %(--- | ||
{ | ||
--- | ||
some text | ||
) | ||
expect(parser.parse(content)).to eq({}) | ||
end | ||
|
||
it "returns empty hash if the frontmatter is not terminated" do | ||
content = %(--- | ||
some text | ||
) | ||
expect(parser.parse(content)).to eq({}) | ||
end | ||
|
||
|
||
it "returns empty hash if no frontmatter" do | ||
content = "hello world" | ||
expect(parser.parse(content)).to eq({}) | ||
end | ||
end |