Module: Mongoid::Votable

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid/votable.rb,
lib/mongoid/votable/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#vote!(value, voter) ⇒ Object



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
# File 'lib/mongoid/votable.rb', line 24

def vote!(value, voter)
  vote = votes.where(voter: voter).first
  if vote
    new_value = vote.value + value
    if new_value == 0
      votes.delete(vote)
      do_vote!(vote, value, :destroyed)
      if block_given?
        yield 0, :destroyed 
      else
        return :destroyed
      end
    else
      vote.inc(:value, value)
      do_vote!(vote, value, :updated)
      if block_given?
        yield vote.value, :updated 
      else
        return :updated
      end
    end
  else
    votes.create(voter: voter, value: value)
    do_vote!(vote, value, :created)
    if block_given?
      yield value, :created
    else
      return :created
    end
  end
end

#voted?(voter) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/mongoid/votable.rb', line 20

def voted?(voter)
  votes.where(voter: voter).first != nil
end