Skip to content

Instantly share code, notes, and snippets.

@mrsweaters
Created July 16, 2012 23:59
Show Gist options
  • Save mrsweaters/3125996 to your computer and use it in GitHub Desktop.
Save mrsweaters/3125996 to your computer and use it in GitHub Desktop.
HTML5 Video Voting backend
class Vote < ActiveRecord::Base
belongs_to :video
belongs_to :user
has_one :comment
validates :vote_is_not_in_same_bar, :presence => {:on => :create}
def self.time_intervals(params)
bars = params[:bars].to_i
groups = Array.new(bars, 0)
vote = Vote.where(:video_id => params[:video_id]).first
interval = 1 if vote.nil?
interval ||= vote.duration / bars
sql = <<-QUERY
SELECT time_interval, COUNT(*) AS cnt
FROM (SELECT FLOOR(time / #{interval}) AS time_interval
FROM votes
WHERE video_id = #{params[:video_id]}) AS vote
GROUP BY time_interval
QUERY
find_by_sql(sql).each do |time|
groups[time.time_interval] = time.cnt
end
groups
end
def vote_is_not_in_same_bar
bars = Video.find(self.video_id).bars
last_vote = Vote.where(:ip_address => self.ip_address).last
interval = self.duration / bars.to_i
created_at = 0 if last_vote.blank?
created_at ||= last_vote['created_at'].to_time.to_i
now = Time.now.to_time.to_i
diff = now - created_at
if diff > interval
return true
else
errors.add_to_base('You just voted!')
end
end
end
class VotesController < ApplicationController
before_filter :authenticate_user!, :except => [:create, :show, :new, :index]
respond_to :html, :json
def index
respond_with(@votes = Vote.all)
end
def show
@votes = Vote.time_intervals(params)
if params[:callback]
output = params[:callback] + '("' + @votes.to_json + '");'
else
output = @votes
end
respond_with do |format|
format.html {}
format.json { render :json => output }
end
end
def new
respond_with(@vote = Vote.new)
end
def edit
@vote = Vote.find params[:id]
end
def create
if params[:callback]
@vote = Vote.new(params[:data][:vote])
output = params[:callback] + '()'
else
@vote = Vote.new params[:vote]
output = @vote
end
@vote.user_id = current_user.id if current_user
respond_with do |format|
if @vote.save
format.json { render :json => output , :status => :created }
else
format.json { render :json => @vote.errors, :status => :unprocessable_entity }
end
end
end
def update
@vote = Vote.find params[:id]
respond_with do |format|
if @vote.update_attributes params[:vote]
format.html { redirect_to @vote, :notice => 'Vote was successfully updated.' }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :xml => @vote.errors, :status => :unprocessable_entity }
end
end
end
def destroy
Vote.destroy params[:id]
respond_to do |format|
format.html { redirect_to votes_url }
format.json { head :ok }
end
end
def destroy_all
Vote.destroy_all(:video_id => params[:video_id])
respond_to do |format|
format.html { redirect_to votes_url }
format.json { head :ok }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment