forked from sunspot/sunspot
/
adapters.rb
83 lines (77 loc) · 2.14 KB
/
adapters.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
module Sunspot #:nodoc:
module Rails #:nodoc:
#
# This module provides Sunspot Adapter implementations for ActiveRecord
# models.
#
module Adapters
class ActiveRecordInstanceAdapter < Sunspot::Adapters::InstanceAdapter
#
# Return the primary key for the adapted instance
#
# ==== Returns
#
# Integer:: Database ID of model
#
def id
@instance.id
end
end
class ActiveRecordDataAccessor < Sunspot::Adapters::DataAccessor
# options for the find
attr_accessor :include, :select
#
# Set the fields to select from the database. This will be passed
# to ActiveRecord.
#
# ==== Parameters
#
# value<Mixed>:: String of comma-separated columns or array of columns
#
def select=(value)
value = value.join(', ') if value.respond_to?(:join)
@select = value
end
#
# Get one ActiveRecord instance out of the database by ID
#
# ==== Parameters
#
# id<String>:: Database ID of model to retreive
#
# ==== Returns
#
# ActiveRecord::Base:: ActiveRecord model
#
def load(id)
@clazz.first(options_for_find.merge(
:conditions => { @clazz.primary_key => id.to_i}
))
end
#
# Get a collection of ActiveRecord instances out of the database by ID
#
# ==== Parameters
#
# ids<Array>:: Database IDs of models to retrieve
#
# ==== Returns
#
# Array:: Collection of ActiveRecord models
#
def load_all(ids)
@clazz.all(options_for_find.merge(
:conditions => { @clazz.primary_key => ids.map { |id| id.to_i }}
))
end
private
def options_for_find
returning({}) do |options|
options[:include] = @include unless @include.blank?
options[:select] = @select unless @select.blank?
end
end
end
end
end
end