Module: Mongoid::Voteable::Voting::ClassMethods

Defined in:
lib/voteable_mongoid/voteable/voting.rb

Instance Method Summary collapse

Instance Method Details

#vote(options) ⇒ votes, ...

Make a vote on an object of this class



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
# File 'lib/voteable_mongoid/voteable/voting.rb', line 18

def vote(options)
  options.symbolize_keys!
  options[:votee_id] = BSON::ObjectId(options[:votee_id]) if options[:votee_id].is_a?(String)
  options[:voter_id] = BSON::ObjectId(options[:voter_id]) if options[:voter_id].is_a?(String)
  options[:value] = options[:value].to_sym
  options[:voteable] = VOTEABLE[name][name]
  
  update_parents = options[:voteable][:update_parents]

  if options[:voteable]
     query, update = if options[:revote]
      revote_query_n_update(options)
    elsif options[:unvote]
      unvote_query_n_update(options)
    else
      new_vote_query_n_update(options)
    end

    if update_parents || options[:votee] || options[:return_votes]
      # If votee exits or need to update parent
      # use Collection#find_and_modify to retrieve updated votes data and parent_ids
      begin
        doc = collection.master.collection.find_and_modify(
          :query => query,
          :update => update,
          :new => true
        )
        # Update new votes data
        votes = doc['votes']
        options[:votee].write_attribute('votes', votes) if options[:votee]
        update_parent_votes(doc, options) if update_parents
        return votes
      rescue
        # Don't update parents if operation fail or no matching object found
        return false
      end
    else
      # Just update and don't care the result
      collection.update(query, update)
    end
  end
end