Class: Diary::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/diary-ruby/parser.rb

Class Method Summary collapse

Class Method Details

.parse(infile) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/diary-ruby/parser.rb', line 5

def self.parse(infile)
  header = []
  body = []
  in_header = true
  split_match = /^---+$/

  Diary.debug("PARSE #{ infile.size } BYTES")

  infile.lines.each do |line|
    if in_header
      if split_match =~ line
        in_header = false
        next
      end

      # check for line
      header << line
    else
      body << line
    end
  end

   = {}

  key_match = /^([A-Za-z_-]+):? (.+)$/
  header.each do |h_line|
    if key_match =~ h_line
      key = $1.strip.downcase
      val = $2.strip

      if /tags/i =~ key
        val = val.split(',').map {|v| v.strip}
      end

      [key] = val
    end
  end

  key = Entry.keygen(['day'], ['time'])
  Diary.debug "KEY #{ key }"
  Diary.debug "METADATA #{ .inspect }"
  Diary.debug "BODY #{ body.join(" ") }"

  return Entry.new(
    day: ['day'],
    time: ['time'],
    tags: ['tags'],
    body: body.join("\n").strip,
    title: ['title'],
    key: key,
  )
end

.parse_file(file) ⇒ Object



58
59
60
61
62
63
64
65
# File 'lib/diary-ruby/parser.rb', line 58

def self.parse_file(file)
  # read
  file.seek(0)
  contents = file.read

  # now parse
  self.parse(contents)
end