Class: Checklister::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/checklister/parser.rb

Overview

Parse a markdown file and return a hash of params.

Examples:

{
  title: "Title",
  body: "## Mardown Body context\n## Checklist\nMardown Body checklist"
}

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Parser

Returns a new instance of Parser.

Parameters:

  • file_path (String)

    the path of the markdown file to parse



12
13
14
# File 'lib/checklister/parser.rb', line 12

def initialize(file_path)
  @file_content = File.open(file_path).read
end

Instance Method Details

#to_paramsHash

Returns a hash of params.

Returns:

  • (Hash)

    a hash of params



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/checklister/parser.rb', line 17

def to_params
  title     = ""
  checklist = []

  @file_content.each_line do |line|
    # Extract a title, when we find the first <h1> header
    if title == "" && line.start_with?("# ")
      title = line.sub("# ", "").sub("\n", "")
    else
      # Then, keep the text intact until the end of the file
      checklist << line
    end
  end

  # Default title, if no <H1> header found
  title = "Checklist" if title == ""

  # Return the parsed text as an object
  { title: title, body: checklist.join }
end