Module: Mongo::Voteable::Voting::ClassMethods

Defined in:
lib/voteable_mongo/voting.rb

Instance Method Summary collapse

Instance Method Details

#vote(options) ⇒ votee, false

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

Returns:

  • (votee, false)


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
# File 'lib/voteable_mongo/voting.rb', line 17

def vote(options)
  validate_and_normalize_vote_options(options)
  options[:voteable] = VOTEABLE[name][name]
  
  if options[:voteable]
     query, update = if options[:revote]
      revote_query_and_update(options)
    elsif options[:unvote]
      unvote_query_and_update(options)
    else
      new_vote_query_and_update(options)
    end

    # http://www.mongodb.org/display/DOCS/findAndModify+Command
    begin
      doc = where(query).find_and_modify(
        update,
        :new => true
      )
    rescue Moped::Errors::OperationFailure
      doc = nil
    end  

    if doc
      update_parent_votes(doc, options) if options[:voteable][:update_parents]
      # Update new votes data
      options[:votee].write_attribute('votes', doc['votes']) if options[:votee]
      options[:votee] || new(doc.as_document)
    else
      false
    end
  end
end