Module: MongoidExt::Voteable
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/mongoid_ext/voteable.rb
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
- #add_vote!(value, voter_id, &block) ⇒ Object
- #remove_vote!(value, voter_id, &block) ⇒ Object
- #vote!(value, voter_id, &block) ⇒ Object
- #voted?(voter_id) ⇒ Boolean
Instance Method Details
#add_vote!(value, voter_id, &block) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/mongoid_ext/voteable.rb', line 52 def add_vote!(value, voter_id, &block) if updates = {self.atomic_position+".votes_count" => 1, self.atomic_position+".votes_average" => value.to_i} if value == 1 updates[self.atomic_position+".votes_up"] = 1 elsif value == -1 updates[self.atomic_position+".votes_down"] = 1 end self._parent.increment(updates) else updates = {:votes_count => 1, :votes_average => value.to_i} if value == 1 updates[:votes_up] = 1 elsif value == -1 updates[:votes_down] = 1 end self.increment(updates) end block.call(value, :add) if block self.on_add_vote(value, voter_id) if self.respond_to?(:on_add_vote) end |
#remove_vote!(value, voter_id, &block) ⇒ Object
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/mongoid_ext/voteable.rb', line 79 def remove_vote!(value, voter_id, &block) if updates = {self.atomic_position+".votes_count" => -1, self.atomic_position+".votes_average" => -value.to_i} if value == 1 updates[self.atomic_position+".votes_up"] = -1 elsif value == -1 updates[self.atomic_position+".votes_down"] = -1 end self._parent.increment(updates) else updates = {:votes_count => -1, :votes_average => -value} if value == 1 updates[:votes_up] = -1 elsif value == -1 updates[:votes_down] = -1 end self.increment(updates) end block.call(value, :remove) if block self.on_remove_vote(value, voter_id) if self.respond_to?(:on_remove_vote) end |
#vote!(value, voter_id, &block) ⇒ Object
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 |
# File 'lib/mongoid_ext/voteable.rb', line 22 def vote!(value, voter_id, &block) value = value.to_i voter_id = voter_id.to_s old_vote = self.votes[voter_id] if !old_vote self.votes[voter_id] = value if self.save add_vote!(value, voter_id, &block) return :created end else if(old_vote != value) self.votes[voter_id] = value if self.save self.remove_vote!(old_vote, voter_id, &block) self.add_vote!(value, voter_id, &block) return :updated end else self.votes.delete(voter_id) if self.save remove_vote!(value, voter_id, &block) return :destroyed end end end end |
#voted?(voter_id) ⇒ Boolean
14 15 16 17 18 19 20 |
# File 'lib/mongoid_ext/voteable.rb', line 14 def voted?(voter_id) if self[:votes] && !self[:votes].empty? self[:votes].include?(voter_id) else self.class.where({:_id => self.id, :"votes.#{voter_id}".exists => true}).exists? end end |