Class: Madness::Search

Inherits:
Object
  • Object
show all
Includes:
Ferret, Ferret::Index, ServerHelper
Defined in:
lib/madness/search.rb

Instance Method Summary collapse

Methods included from ServerHelper

#config, #docroot, #log

Constructor Details

#initialize(path = nil) ⇒ Search

Returns a new instance of Search.



10
11
12
# File 'lib/madness/search.rb', line 10

def initialize(path=nil)
  @path = path || docroot
end

Instance Method Details

#build_indexObject



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/madness/search.rb', line 18

def build_index
  Dir.mkdir index_dir unless Dir.exist? index_dir

  index = Index.new path: index_dir, create: true

  Dir["#{@path}/**/*.md"].each do |file|
    record = { file: file, content: searchable_content(file) }
    index << record unless skip_index? file
  end

  index.optimize()                                
  index.close()
end

#has_index?Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/madness/search.rb', line 14

def has_index?
  Dir.exist? index_dir
end

#index_dirObject



59
60
61
# File 'lib/madness/search.rb', line 59

def index_dir
  "#{@path}/_index"
end

#remove_index_dirObject



54
55
56
57
# File 'lib/madness/search.rb', line 54

def remove_index_dir
  return unless Dir.exist? index_dir
  FileUtils.rm_r index_dir
end

#search(query) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/madness/search.rb', line 32

def search(query)
  index = Index.new path: index_dir

  results = []
  index.search_each(query, limit: 20) do |doc_id, score| 
    filename = index[doc_id][:file].sub("#{@path}/", '')[0...-3]
    highlights = index.highlight "content:(#{query.tr(' ',' OR ')}) ", doc_id, field: :content,
      pre_tag: "<strong>", post_tag: "</strong>",
      excerpt_length: 100
    
    results << { 
      score: score, 
      file: file_url(filename),
      label: file_label(filename),
      highlights: highlights
    }
  end

  index.close()
  results
end