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



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
# 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_one_and_update(update, {return_document: :after})
    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