1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
module VotedFor
  def votes
    @votes = logged_in? ? current_user.votes : (session[:votes] ? Vote.find(session[:votes]) : [])
  end

  def add_session_vote(vote)
    (session[:votes] ||= []) << vote.id unless logged_in?
  end

  def remove_session_vote(vote)
    Vote.find(session[:votes]).delete_if{|v| v[:ballot_candidate_id] == vote[:ballot_candidate_id]} if !logged_in? && !session[:votes].nil?
  end

  # pass {:type => 'ballot', :id => 1234}
  def voted?(opts)
    logged_in? ? (return user_voted?(opts)) : (return anonymously_voted?(opts))
  end

  def anonymously_voted?(opts)
    Vote.find(session[:votes]).each{|v| return v if v["#{opts[:type]}_id"] == opts[:id] } unless session[:votes].nil?
    nil
  end

  def user_voted?(opts)
    return current_user.votes.find(:first, :conditions => "#{opts[:type]}_id = #{opts[:id]}")
    nil
  end

  def update_logged_out_votes
    if logged_in? && !session[:votes].nil?
      Vote.find(session[:votes]).each do |vote|
        if anonymously_voted?({:type => :ballot, :id => vote.ballot_candidate_id}).nil?
          vote.update_attribute(:user_id, current_user.id)
        else
          vote.destroy
        end

        remove_session_vote(vote)
      end
    end
  end
end