forked from Empact/sunspot_mongoid
/
mongoid.rb
91 lines (81 loc) · 2.21 KB
/
mongoid.rb
1
2
3
4
5
6
7
8
9
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
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
require 'sunspot'
require 'mongoid'
require 'sunspot/rails'
# == Examples:
#
# class Post
# include Mongoid::Document
# field :title
#
# include Sunspot::Mongoid
# searchable do
# text :title
# end
# end
#
module Sunspot
module Mongoid
def self.included(base)
base.class_eval do
extend Sunspot::Rails::Searchable::ActsAsMethods
extend Sunspot::Mongoid::ActsAsMethods
Sunspot::Adapters::DataAccessor.register(DataAccessor, base)
Sunspot::Adapters::InstanceAdapter.register(InstanceAdapter, base)
after_destroy :_remove_index
after_save :_update_index
end
end
module ActsAsMethods
# ClassMethods isn't loaded until searchable is called so we need
# call it, then extend our own ClassMethods.
def searchable (opt = {}, &block)
super
extend ClassMethods
end
end
module ClassMethods
# The sunspot solr_index method is very dependent on ActiveRecord, so
# we'll change it to work more efficiently with Mongoid.
def solr_index(opts={})
batch_size = opts[:batch_size] || 50 # Sunspot.config.indexing.default_batch_size
0.step(count, batch_size) do |offset|
Sunspot.index(limit(batch_size).skip(offset))
end
Sunspot.commit
end
def solr_index_orphans(opts={})
batch_size = opts[:batch_size] || 50 #Sunspot.config.indexing.default_batch_size
count = self.count
indexed_ids = solr_search_ids { paginate(:page => 1, :per_page => count) }.to_set
only(:id).each do |object|
indexed_ids.delete(object.id)
end
indexed_ids.to_a
end
end
class InstanceAdapter < Sunspot::Adapters::InstanceAdapter
def id
@instance.id.to_s
end
end
class DataAccessor < Sunspot::Adapters::DataAccessor
def load(id)
criteria(id).first
end
def load_all(ids)
criteria(ids)
end
private
def criteria(ids)
c = @clazz.criteria
c.respond_to?(:for_ids) ? c.for_ids(ids) : c.id(ids)
end
end
def _remove_index
Sunspot.remove! self
end
def _update_index
Sunspot.index! self
end
end
end