Class: ActsAsCaesar::MongoidPersistence

Inherits:
Object
  • Object
show all
Defined in:
lib/acts_as_caesar/services/mongoid_persistence.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, id) ⇒ MongoidPersistence

Returns a new instance of MongoidPersistence.



10
11
12
13
# File 'lib/acts_as_caesar/services/mongoid_persistence.rb', line 10

def initialize(klass, id)
  @klass = klass
  @id = id
end

Class Method Details

.can_handle?(klass) ⇒ Boolean

Returns:

  • (Boolean)


4
5
6
7
# File 'lib/acts_as_caesar/services/mongoid_persistence.rb', line 4

def can_handle?(klass)
  defined?(Mongoid) && defined?(Mongoid::Document) &&
  klass.included_modules.include?(Mongoid::Document)
end

Instance Method Details

#candidateObject



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
# File 'lib/acts_as_caesar/services/mongoid_persistence.rb', line 19

def candidate
  return @candidate if defined?(@candidate)
  
  relations = []
  klass = @klass
  
  # loop back through nesting, appending relations
  while (embedded_relations = klass.relations.select { |k,v| v.macro == :embedded_in }) && embedded_relations.size > 0
    relation = embedded_relations.values.first
    klass = relation.class_name.constantize
    relations << relation.inverse_of
  end
  
  # start at the root document
  scope = klass
  
  # for each nested relation
  while relation = relations.pop
    key = relation.to_s
    if relations.size > 0
      key += "."
      key += relations.reverse.join(".")
    end
    key += "._id"
    # append the condition
    scope = scope.where(key => BSON::ObjectId(@id)).first.send(relation)
  end
  
  # find the final object
  @candidate = scope.find(@id)
end

#update_scoreObject



15
16
17
# File 'lib/acts_as_caesar/services/mongoid_persistence.rb', line 15

def update_score
  candidate.update_attribute(:score, candidate.total_candidate_score)
end