Class: ActsAsCaesar::Vote

Inherits:
Object
  • Object
show all
Defined in:
lib/acts_as_caesar/objects/vote.rb

Direct Known Subclasses

NegativeVote, NoVote, PositiveVote

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs) ⇒ Vote

Returns a new instance of Vote.



34
35
36
# File 'lib/acts_as_caesar/objects/vote.rb', line 34

def initialize(attrs)
  @attrs = attrs
end

Class Method Details

.find(options) ⇒ Object



6
7
8
# File 'lib/acts_as_caesar/objects/vote.rb', line 6

def find(options)
  from_value(Persistence.vote_value(options), options)
end

.from_value(value, options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/acts_as_caesar/objects/vote.rb', line 10

def from_value(value, options = {})
  case value
  when 1
    PositiveVote
  when -1
    NegativeVote
  else
    NoVote
  end.new(options)
end

.valueObject



21
22
23
# File 'lib/acts_as_caesar/objects/vote.rb', line 21

def value
  0
end

Instance Method Details

#candidateObject



30
31
32
# File 'lib/acts_as_caesar/objects/vote.rb', line 30

def candidate
  @attrs[:candidate]
end

#to_json(*args) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/acts_as_caesar/objects/vote.rb', line 59

def to_json(*args)
  {
    voter: voter.to_json,
    candidate: candidate.to_json,
    value: value
  }
end

#update(new_value) ⇒ Object

Raises:

  • (ArgumentError)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/acts_as_caesar/objects/vote.rb', line 42

def update(new_value)
  raise ArgumentError, "Only accepts Integer objects" unless new_value.kind_of?(Integer)
  # don't change if the values already match
  return self if new_value == value
  # set the new value
  Persistence.set_vote_value(new_value, @attrs)
  # if the value has increased
  if new_value > value
    Persistence.increment_total_votes_on(candidate)
  # if the value has decreased
  elsif new_value < value
    Persistence.decrement_total_votes_on(candidate)
  end
  # return the new value object
  self.class.from_value(new_value, @attrs)
end

#valueObject



38
39
40
# File 'lib/acts_as_caesar/objects/vote.rb', line 38

def value
  self.class.value
end

#voterObject



26
27
28
# File 'lib/acts_as_caesar/objects/vote.rb', line 26

def voter
  @attrs[:voter]
end