Module: Mongoid::Voter

Extended by:
ActiveSupport::Concern
Defined in:
lib/voteable_mongoid/voter.rb

Instance Method Summary collapse

Instance Method Details

#unvote(options) ⇒ Object

Cancel the vote on a votee

Parameters:

  • votee (Object)

    the votee to be unvoted



45
46
47
48
49
50
51
52
# File 'lib/voteable_mongoid/voter.rb', line 45

def unvote(options)
  unless options.is_a?(Hash)
    options = { :votee => options }
  end
  options[:unvote] = true
  options[:revote] = false
  vote(options)
end

#vote(options, value = nil) ⇒ Object

Vote on a votee

Parameters:

  • vote_value (:up, :down)

    vote up or vote down, nil to unvote

  • options (Hash, Object)

    the hash containing the votee, or the votee itself



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/voteable_mongoid/voter.rb', line 58

def vote(options, value = nil)
  if options.is_a?(Hash)
    votee = options[:votee]
  else
    votee = options
    options = { :votee => votee, :value => value }
  end

  if votee
    options[:votee_id] = votee.id
    votee_class = votee.class
  else
    votee_class = options[:votee_type].classify.constantize
  end
  
  if options[:value].nil?
    options[:unvote] = true
    options[:value] = vote_value(options)
  else
    options[:revote] = options.has_key?(:revote) ? !options[:revote].blank? : voted?(options)
  end
  
  options[:voter] = self
  options[:voter_id] = id

  ( votee || votee_class ).vote(options)
end

#vote_value(options) ⇒ Symbol?

Get the voted value on a votee

Parameters:

  • options (Hash, Object)

    the hash containing the votee, or the votee itself

Returns:

  • (Symbol, nil)

    :up or :down or nil if not voted



31
32
33
34
35
36
37
38
39
40
# File 'lib/voteable_mongoid/voter.rb', line 31

def vote_value(options)
  votee = unless options.is_a?(Hash)
    options
  else
    options[:votee] || options[:votee_type].classify.constantize.only(:votes).where(
      :_id => options[:votee_id]
    ).first
  end
  votee.vote_value(_id)
end

#voted?(options) ⇒ true, false

Check to see if this voter voted on the votee or not

Parameters:

  • options (Hash, Object)

    the hash containing the votee, or the votee itself

Returns:

  • (true, false)

    true if voted, false otherwise



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/voteable_mongoid/voter.rb', line 9

def voted?(options)
  unless options.is_a?(Hash)
    votee_class = options.class
    votee_id = options.id
  else
    votee = options[:votee]
    if votee
      votee_class = votee.class
      votee_id = votee.id
    else
      votee_class = options[:votee_type].classify.constantize
      votee_id = options[:votee_id]
    end
  end
  
  votee_class.voted_by(self).where(:_id => votee_id).count == 1
end