Sha256: 71d3c0ae80d1421f887bae65b76964364cf2474b008ccf8cb4734e049cd1d042

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

module SanteyVote
  module Voteable

      def self.included(base)
        base.extend ClassMethods
      end

      module ClassMethods
        def santey_vote
          has_many :votes, :as => :voteable, :dependent => :destroy
          include SanteyVote::Voteable::InstanceMethods
          extend SanteyVote::Voteable::SingletonMethods
        end
      end
      
      module SingletonMethods
        def find_votes_cast_by_user(user)
          voteable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
          Vote.find(:all,
            :conditions => ["user_id = ? and voteable_type = ?", user.id, voteable],
            :order => "created_at DESC"
          )
        end
      end
      
      module InstanceMethods
        def votes_for
          votes = Vote.find(:all, :conditions => [
            "voteable_id = ? AND voteable_type = ? AND vote = TRUE",
            id, self.class.name
          ])
          votes.size
        end
        
        def votes_against
          votes = Vote.find(:all, :conditions => [
            "voteable_id = ? AND voteable_type = ? AND vote = FALSE",
            id, self.class.name
          ])
          votes.size
        end
        
        # Same as voteable.votes.size
        def votes_count
          self.votes.size
        end
        
        def users_who_voted
          users = []
          self.votes.each { |v|
            users << v.user
          }
          users
        end
        
        def voted_by_user?(user)
          rtn = false
          if user
            self.votes.each { |v|
              rtn = true if user.id == v.user_id
            }
          end
          rtn
        end
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
santey_vote-0.1.1 lib/santey_vote/voteable.rb