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

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

Instance Method Summary (collapse)

Instance Method Details

- (votes, ...) vote(options)

Make a vote on an object of this class

Parameters:

  • options (Hash)

    a hash containings:

    • :votee_id: the votee document id

    • :voter_id: the voter document id

    • :value: :up or :down

    • :revote: if true change vote vote from :up to :down and vise versa

    • :unvote: if true undo the voting

    • :return_votes: if true always return updated votes data

Returns:

  • (votes, false, nil)


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