Module: Bergamasco::Markdown

Defined in:
lib/bergamasco/markdown.rb

Constant Summary collapse

YAML_FRONT_MATTER_REGEXP =

split file into YAML frontmatter and content

/\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m

Class Method Summary collapse

Class Method Details

.extract_references(html) ⇒ Object

expects a references list generated by pandoc



64
65
66
67
# File 'lib/bergamasco/markdown.rb', line 64

def self.extract_references(html)
  doc = Nokogiri::HTML(html)
  doc.xpath('//div[@id="refs"]/div/@id').map { |ref| ref.value[4..-1] }
end

.join_yaml_frontmatter(metadata, content) ⇒ Object



18
19
20
# File 'lib/bergamasco/markdown.rb', line 18

def self.join_yaml_frontmatter(, content)
  .to_yaml + "---\n" + content
end

.read_yaml(filepath) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/bergamasco/markdown.rb', line 31

def self.read_yaml(filepath)
  unless File.exist?(filepath)
    parentdir = Pathname.new(filepath).parent
    FileUtils.mkdir_p parentdir
    FileUtils.touch filepath
  end

  file = IO.read(filepath)
  SafeYAML.load(file)
end

.read_yaml_for_doi_metadata(filepath, options = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/bergamasco/markdown.rb', line 42

def self.(filepath, options={})
  return nil unless File.exist?(filepath)

  file = IO.read(filepath)
  yaml = SafeYAML.load(file)
  return nil unless yaml.present?

  keys = options[:keys] || ["title", "author", "date", "tags", "summary", "accession_number", "doi", "type", "version", "references", "published"]
   = yaml.extract!(*keys).compact

  content = YAML_FRONT_MATTER_REGEXP.match(file).post_match
  html = Bergamasco::Pandoc.convert(content, options)
  ["summary"] = Bergamasco::Summarize.summary_from_html(html, options)
  ["references"] = extract_references(html)
  
end

.split_yaml_frontmatter(file) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/bergamasco/markdown.rb', line 6

def self.split_yaml_frontmatter(file)
  return file unless match = YAML_FRONT_MATTER_REGEXP.match(file)

   = SafeYAML.load(file)
  content = match.post_match
  [, content]
end

.update_file(filepath, new_metadata) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/bergamasco/markdown.rb', line 22

def self.update_file(filepath, )
  file = IO.read(filepath)
  , content = split_yaml_frontmatter(file)
   = update_yaml_frontmatter(, )
  new_file = join_yaml_frontmatter(, content)
  IO.write(filepath, new_file)
  
end

.update_yaml_frontmatter(metadata, new_metadata) ⇒ Object



14
15
16
# File 'lib/bergamasco/markdown.rb', line 14

def self.update_yaml_frontmatter(, )
  .merge().compact
end

.write_yaml(filepath, content) ⇒ Object



59
60
61
# File 'lib/bergamasco/markdown.rb', line 59

def self.write_yaml(filepath, content)
  IO.write(filepath, content.to_yaml)
end