Class: Jekyll::J1LunrSearch::Indexer

Inherits:
Generator
  • Object
show all
Defined in:
lib/starter_web/_plugins/index/lunr.rb

Overview

noinspection RubyTooManyInstanceVariablesInspection,RubyInterpreter

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Indexer

Returns a new instance of Indexer.



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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/starter_web/_plugins/index/lunr.rb', line 25

def initialize(config = {})
  super(config)

  @mode = config['environment']
  @template = config['theme']

  @project_path                   = File.join(File.dirname(__FILE__)).sub('_plugins/index', '')
  @module_config_path             = File.join(@project_path, config['data_dir'], 'modules')
  @j1_config_path                 = config['data_dir']

  @j1_config                      = YAML::load(File.open(File.join(@j1_config_path, 'j1_config.yml')))
  @module_config_default          = YAML::load(File.open(File.join(@module_config_path, 'defaults', 'lunr.yml')))
  @module_config_user             = YAML::load(File.open(File.join(@module_config_path,'lunr.yml')))

  @module_config_default_settings = @module_config_default['defaults']
  @module_config_user_settings    = @module_config_user['settings']
  @module_config                  = @module_config_default_settings.merge!(@module_config_user_settings)

  @lunr_config = {
    'excludes' => [],
    'strip_index_html' => false,
    'min_length' => 3,
    'stopwords' => 'stopwords.txt',
    'fields' => {
      'title' => 10,
      'tagline' => 10,
      'tags' => 20,
      'categories' => 20,
      'description' => 20,
      'body' => 1
    }
  }.merge!(@module_config || {})

  @lunr_config.merge!(@j1_config['posts'])

  @module_dir = @lunr_config['module_dir']
  @index_dir  = @lunr_config['index_dir']
  @index_name = @lunr_config['index_name']

  # calculate the module path
  # if NO template GEM is used (dev system), @project_path points
  # in the project folder, otherwise (runtime system) to the Ruby
  # GEM installation folder!
  #
  if @template.nil?
    @project_path = File.join(File.dirname(__FILE__), '../../', @module_dir)
  else
    @gem_path    = `bundle info --path j1-template`
    @project_path = File.join(@gem_path.chomp, @module_dir)
  end

  @lunr_path = File.join(@project_path, 'lunr.min.js')
  raise "Could not find #{@lunr_path}" unless File.exist?(@lunr_path)

  # set NodeJS for JS runtime explicitely
  ExecJS.runtime = ExecJS::Runtimes::Node
  lunr_src = open(@lunr_path).read
  ctx = ExecJS.compile(lunr_src)

  @docs = {}
  @excludes = @lunr_config['excludes']

  # if web host supports index.html as default doc, then
  # optionally exclude it from the url
  #
  @strip_index_html = @lunr_config['strip_index_html']

  # @strip_categories configuration
  #
  @strip_categories = @lunr_config['category_blacklist']
  @stripped_categories = @strip_categories.join(',').gsub!(',', ' ')

  # stop word exclusion configuration
  #
  @min_length = @lunr_config['min_length']
  @stopwords_file = @lunr_config['stopwords']

end

Instance Method Details

#generate(site) ⇒ Object

Index all pages except pages matching any value in config or with frontmatter settings (exclude_from_search: true)



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/starter_web/_plugins/index/lunr.rb', line 107

def generate(site)

  @site = site
  index_dest = @site.instance_variable_get(:@dest)
  rebuild = @module_config['rebuild']
  index_file = index_dest + @module_config['index_file']

  if plugin_disabled?
    Jekyll.logger.info 'J1 Lunr:', 'disabled'
    return
  else
    Jekyll.logger.info 'J1 Lunr:', 'enabled'
    Jekyll.logger.info 'J1 Lunr:', 'generate search index'
  end

  if @module_config['rebuild'] == false
    if File.exist?(index_file)
      Jekyll.logger.info 'J1 Lunr:', 'rebuild index disabled'
      # Keep the index file from being cleaned by Jekyll
      #
      site.static_files << SearchIndexFile.new(site, site.dest, '/', @module_config['index_file'])
      return
    end
  end

  # gather posts and pages
  #
  items = pages_to_index(site)
  content_renderer = PageRenderer.new(site)
  # index = []
  # rebuild = @module_config['rebuild']

  index_js = open(@lunr_path).read

  # NOTE: all settings must be added within the index function
  #
  index_js << 'var idx = lunr(function() {'

  @lunr_config['fields'].each_pair do |name, boost|
      index_js << "this.field('#{name}', {'boost': #{boost}});"
  end

  items.each_with_index do |item, i|
    entry = SearchEntry.create(item, content_renderer)

    entry.strip_index_suffix_from_url! if @strip_index_html
    entry.strip_stopwords!(stopwords, @min_length) if File.exist?(@stopwords_file)

    doc = {
      'id'          => i,
      'title'       => entry.title,
      'tagline'     => entry.tagline,
      'url'         => entry.url,
      'date'        => entry.date,
      'tags'        => entry.tags,
      'categories'  => entry.categories,
      'description' => entry.description,
      'is_post'     => entry.is_post,
      'body'        => entry.body
    }

    # remove unwanted categories (if any)
    #
    doc['categories'] -= @strip_categories unless doc['categories'] == nil

    index_js << 'this.add(' << ::JSON.generate(doc, quirks_mode: true) << ');'

    # reduce the size of the doc array by deleting the body key
    #
    doc.delete('body')
    @docs[i] = doc

  end
  index_js << '});'


  filename  = File.join(@index_dir, "#{@index_name}")
  ctx       = ExecJS.compile(index_js)
  index     = ctx.eval('JSON.stringify(idx)')

  total     = {
    'docs'  => @docs,
    'index' => ::JSON.parse(index, {:max_nesting => false})
  }
  filepath  = File.join(site.dest, filename)

  # create data path if not already exists
  #
  FileUtils.mkdir_p(File.dirname(filepath))
  File.open(filepath, 'w') { |f| f.write(JSON.dump(total)) }
#       Jekyll.logger.info 'J1 Lunr:', "finished, index ready."
  added_files = [filename]

  # Keep the written files from being cleaned by Jekyll
  #
  added_files.each do |fname|
    site.static_files << SearchIndexFile.new(site, site.dest, '/', fname)
  end
end