Class: Jekyll::SearchFileGenerator

Inherits:
Generator
  • Object
show all
Defined in:
lib/jekyll_build_search.rb

Instance Method Summary collapse

Instance Method Details

#build_post_hashes(post, converter) ⇒ Object



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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/jekyll_build_search.rb', line 27

def build_post_hashes(post, converter)
  post_hashes = []
  curr_post = nil
  curr_hash = {}
  curr_hash["content"] = []

  converted_lines = post.content.split("\n").map do |line|

    curr_hash["content"] << line

    # skip code blocks
    in_code_block = !in_code_block if line.match(/^```/)
    next line if in_code_block

    # drop lines that aren't markdown headers
    matched = line.match(/^(#+) /)
    next line unless matched

    # drop headers that don't start with dates
    DateTime.parse(line.strip) rescue next line

    # pretty format dates
    date = DateTime.parse(line.strip)
    yearmonth = date.strftime("%Y_%m")
    iddate = date.strftime("%Y%m%d")
    displaydate = date.strftime("%b %e, %Y")

    # we've found a new entry, remove it from the previous entry's lines
    curr_hash["content"].pop()

    # extract project tags and flatten into a single array
    tags = line.strip.scan(/#([a-zA-Z0-9._-]{3,} ?)/).flatten(1)

    if !curr_post.nil?
      curr_hash["content"] = converter.convert(curr_hash["content"].join("\n"))
      post_hashes << curr_hash
    end

    curr_hash = {}
    curr_hash["content"] = []
    curr_hash["title"] = displaydate
    curr_hash["url"] = "/log/#{yearmonth}/##{iddate}"
    curr_hash["tags"] = tags

    curr_post = date
  end
  return post_hashes
end

#generate(site) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/jekyll_build_search.rb', line 8

def generate(site)
  output = [{"title" => "Test"}]

  path = Pathname.new(site.dest) + "search.json"

  converter = site.find_converter_instance(::Jekyll::Converters::Markdown)
  search_list = []

  site.posts.docs.reverse_each do |post|
    search_list.push(*build_post_hashes(post, converter))
  end

  FileUtils.mkdir_p(File.dirname(path))
  File.open(path, 'w') do |f|
   f.write(search_list.to_json)
  end
  site.keep_files << "search.json"
end