Class: Middleman::Lunr::Indexer

Inherits:
Object
  • Object
show all
Defined in:
lib/middleman-lunr/indexer.rb

Instance Method Summary collapse

Constructor Details

#initialize(extension) ⇒ Indexer

Returns a new instance of Indexer.



6
7
8
# File 'lib/middleman-lunr/indexer.rb', line 6

def initialize(extension)
  @extension = extension
end

Instance Method Details

#generate(options) ⇒ Object



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
57
58
59
60
61
62
63
64
# File 'lib/middleman-lunr/indexer.rb', line 10

def generate(options)
  docs = []
  fields = []
  map = {}

  if options[:body]
    fields.push(:body)
  end

  options[:data].each do |d|
    fields.push(d)
  end

  @extension.sitemap.resources.each do |res|
    if res.data[:index]
      doc = { id: res.url.to_s }
      key = res.url.to_s
      data = {}

      if options[:body]
        doc[:body] = File.read(res.source_file)
      end

      options[:data].each do |d|
        doc[d] = res.data[d]
        data[d.to_s] = res.data[d]
      end

      docs << doc
      map[key] = data
    end
  end

  cxt = V8::Context.new
  cxt.load(File.expand_path('../../../js/lunr.min.js', __FILE__))
  cxt.eval('lunr.Index.prototype.dumpIndex = function(){return JSON.stringify(this.toJSON());}')
  ref = cxt.eval('lunr')

  lunr_conf = proc do |this|
    this.ref('id')
    fields.each do |name|
      this.field(name) #, {:boost => boost})
    end
  end

  idx = ref.call(lunr_conf)

  docs.each do |doc|
    idx.add(doc)
  end

  data = JSON.parse(idx.dumpIndex(), max_nesting: false)

  { index: data, map: map }
end