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.



8
9
10
# File 'lib/madness/search.rb', line 8

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

Instance Method Details

#build_indexObject



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

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|
    index << { file: file, content: File.read(file) }
  end

  index.optimize()                                
  index.close()
end

#has_index?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/madness/search.rb', line 12

def has_index?
  Dir.exist? index_dir
end

#index_dirObject



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

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

#remove_index_dirObject



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

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

#search(query) ⇒ Object



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

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: "", post_tag: "",
      excerpt_length: 100
    
    highlights.map! { |excerpt| CGI.escapeHTML excerpt } if highlights

    results << { 
      score: score, 
      file: filename,
      label: filename.gsub("/", " / "),
      highlights: highlights
    }
  end

  index.close()
  results
end