Sha256: 513fdf81ff3996861f0d785d0e3156213846e884780722e6c7e41999239976d7

Contents?: true

Size: 911 Bytes

Versions: 2

Compression:

Stored size: 911 Bytes

Contents

class Poll < ::Renderable
  include E9Polls::Model

  has_many :poll_answers

  accepts_nested_attributes_for :poll_answers, :allow_destroy => true, :reject_if => :reject_answer?

  validates :template, :presence => true

  def vote
    nil
  end

  def as_json(options={})
    {}.tap do |hash|
      hash[:id]       = self.id,
      hash[:name]     = self.name,
      hash[:question] = self.question,
      hash[:answers]  = self.answers,
      hash[:errors]   = self.errors
    end
  end

  def question
    template
  end

  def answers
    poll_answers
  end

  def vote=(id)
    poll_answers.find_by_id(id).try(:vote!)
  end

  def votes
    poll_answers.sum(:votes)
  end

  def percentage_for(poll_answer)
    votes.zero? ? 0 : (poll_answer.votes.to_f / votes * 100).round(2)
  end

  protected

  def reject_answer?(attributes)
    attributes.keys.member?(:value) && attributes[:value].blank?
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
e9_polls-1.0.2 app/models/poll.rb
e9_polls-1.0.1 app/models/poll.rb