<repo_name>choww/arbitrator<file_sep>/app/models/vote.rb
class Vote < ActiveRecord::Base
  belongs_to :user
  belongs_to :question
  validates :question_id, presence: true
  validates :user_id, presence: true 
  validates :value, presence: true
  #validate :no_new_votes_if_expired
  
  ## CUSTOM VALIDATIONS ##
  def no_new_votes_if_expired
    if question && question.expired?
      errors.add(:question, "can't be voted on if expired")
    end    
  end 

end
<file_sep>/Rakefile
require 'rake'
require "sinatra/activerecord/rake"
require "yaml"
require ::File.expand_path('../config/environment', __FILE__)

Rake::Task["db:create"].clear
Rake::Task["db:drop"].clear

database_config = YAML.load_file(APP_ROOT.join('config', './database.yml'))

desc "create the database"
task "db:create" do
  system("psql -U #{database_config['development']['username']} -d postgres -c \"create database arbitrator\"")
end

desc "drop the database"
task "db:drop" do
  system('psql -U testuser -d postgres -c "drop database arbitrator"')
end

desc 'Retrieves the current schema version number'
task "db:version" do
  puts "Current version: #{ActiveRecord::Migrator.current_version}"
end
<file_sep>/app/app_helper.rb
helpers do
  def logged_in?
    !session[:id].nil?
  end

  def current_user
   # uid = logged_in? ? 
    @user = logged_in? ? User.find(session[:id]) : User.new
  end

  def created?(question)
    current_user == question.user 
  end

  def tagged?(question)
    if question.tagged_user 
      current_user.username == question.tagged_user
    end
  end

  def get_user_questions(user,status)
    Question.where(user_id: user.id, resolved: status).order(created_at: :desc)
  end

  def get_tagged_questions(user, status)
    Question.where(resolved: status, tagged_user: user.username).order(created_at: :desc)
  end

  def curr_category
    filter = Question.where(category: session[:category])
    filter.exists? ? filter :  Question.all 
  end

  # where option is 0 or 1
  def winner?(question, option)
    hi_score = [question.vote_count(0), question.vote_count(1)].max
    question.vote_count(option) == hi_score
  end

  def draw?(question)
    question.vote_count(0) == question.vote_count(1)
  end

  def popular_questions
    Question.all.sort {|q1, q2| q2.votes.count <=> q1.votes.count}
  end

  #def format_time(time)
  #  local_time = time.getlocal
  #  (Time.now - local_time).abs
  #end
 
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
  has_many :questions
  has_many :votes
  validates :username, presence: true
  validates :email, presence: true
  validates :password, presence: true
  
  def add_or_update_vote(question, option)
    get_vote = Vote.find_or_create_by(user_id: id, question_id: question)
    get_vote.value = option
    get_vote
  end

end
<file_sep>/app/actions.rb
# For voting create conditional if vote.user_id && vote.question_id then crash
before do
  current_user
end
### FOR TEST PAGE ###

get '/test' do
  questions = Question.all
  @questions = questions.order(created_at: :desc)
  erb :test
end

### THE REAL ROUTES ###

##################################
#Gets                            #
##################################

get '/' do
  @questions = curr_category.order(created_at: :desc)
  erb :index
end

get '/category/:cat_name' do
  if params[:cat_name] == 'top'
    session[:category] = 'top'
    @questions = popular_questions
  else
    session[:category] = params[:cat_name]
    @questions = curr_category.order(created_at: :desc)
  end
  erb :index
end

get '/login' do
  erb :not_logged_in
end

get '/login/:id' do
  session[:id] = params[:id]
  session[:category] = nil
  redirect '/'
end

get '/logout' do 
  session[:id] = nil
  session[:category] = nil
  redirect '/'
end

get '/questions/new' do
  @question = Question.new
  erb :'/questions/new'
end

get '/:username' do
  @user = User.find_by(username: params[:username])
  if @user
    @live_questions = get_user_questions(@user, false)
    @expired_questions = get_user_questions(@user, true)
    @live_tagged = get_tagged_questions(@user, false)
    @expired_tagged = get_tagged_questions(@user, true)
    erb :'users/show'
  end
end

##################################
#Delete                          #
##################################

delete '/questions/:qid/delete' do
  if request.xhr?
    content_type :json   
    @question = Question.find(params[:qid])
    @question.destroy
    {success: true, id: @question.id, message: "question delete"}.to_json
  end
end

##################################
#Posts                           #
##################################

post '/' do
  params[:time].to_i unless params[:time].nil?
  @question = current_user.questions.new(params[:question])

 if @question.save
    redirect '/'
  else
    erb :'/questions/new'
  end
end

post '/questions/:qid/vote' do
  content_type :json
  @question = Question.find(params[:qid].to_i)
  @vote = current_user.add_or_update_vote(@question.id, params[:option].to_i)
  @vote.save
  array = []
  array << @question.vote_count(0)
  array << @question.vote_count(1)
  array.to_json
end

post '/questions/:qid/edit' do
  @question = current_user.questions.find(params[:qid])
  @question.attributes = {
  #  tagged_user: "",
    time: params[:time].to_i,
    resolved: false
  }
  if @question.save
    redirect request.referer
  else
    flash[:notice] = @question.errors.full_messages
    redirect request.referer
  end
end
<file_sep>/db/migrate/20160227013744_change_time.rb
class ChangeTime < ActiveRecord::Migration
  def change
    change_column :questions, :time, :integer, default: 5
  end
end
<file_sep>/db/migrate/20160226203545_add_tagged_user_to_questions.rb
class AddTaggedUserToQuestions < ActiveRecord::Migration
  def change
    add_column :questions, :tagged_user, :string
  end
end
<file_sep>/spec/spec_helper.rb
require 'rspec'
require 'active_record'

require_relative '../app/models/question'
require_relative '../app/models/vote'
require_relative '../app/models/user'

<file_sep>/db/seeds.rb
#For populating test data for db

############
#Test Users#
############
user_a = User.create(username: "CrashOverride", email: "<EMAIL>", password: "<PASSWORD>")
user_b = User.create(username: "ZeroCool", email: "<EMAIL>", password: "<PASSWORD>")
user_c = User.create(username: "CerealKiller", email: "<EMAIL>", password: "<PASSWORD>")

################
#Test Questions#
################
q_a = user_a.questions.create(category: "sports", tagged_user: "", content: "Pippen v. Jordan", time: 60, option_a: "Pippen", option_b: "Jordan")


############
#Test Votes#
############
#No user_a
v_a = user_b.votes.create(value: 1, question_id: q_a.id)
v_b = user_c.votes.create(value: 0, question_id: q_a.id)
<file_sep>/public/javascript/application.js
$(document).ready(function() {
  $('select').material_select();

  $('.button-collapse').sideNav();

  $('.delete-form').submit(function(e) {
    e.preventDefault();

    var qid = $(this).attr('question-id');
    $.post('/questions/' + qid + '/delete', {_method: 'delete'}).done(
      console.log('success')
    );
    $(this).closest('.question-container').remove();
    });


  $('.thumb-up').click(function() {
    var thumb = (this);
    var qid = $(this)[0].id;
    var value = $(this)[0].value;
    $.post('/questions/' + qid + '/vote', {option: value}).done(function (vote) {
      $(thumb).closest('.question-container').find('.left-vote').text(vote[0]);
      $(thumb).closest('.question-container').find('.right-vote').text(vote[1]);
    });
    if (value == 0) {
      $(thumb).closest('.question-container').find('.right-button').children().addClass('red accent-2');
      $(thumb).closest('.question-container').find('.right-button').children().removeClass('green darken-1');
      $(thumb).closest('.question-container').find('.right-button').children().html("<i class='check material-icons'>thumb_up</i>");
    } else if (value == 1) {
      $(thumb).closest('.question-container').find('.left-button').children().addClass('red accent-2');
      $(thumb).closest('.question-container').find('.left-button').children().removeClass('green darken-1');
      $(thumb).closest('.question-container').find('.left-button').children().html("<i class='check material-icons'>thumb_up</i>");;
    }
    $(thumb).html("<i class='check material-icons'>done</i>");
    $(thumb).addClass('green darken-1');
    $(thumb).removeClass('red accent-2');
  });

  $.timeago.settings.allowFuture = true;
  $("time.timeago").timeago();
});
<file_sep>/spec/questions_spec.rb
require_relative 'spec_helper'

describe Question do

  describe '#expire_time' do
    it '' do

    end
  end
end
<file_sep>/db/migrate/20160225032036_add_questions.rb
class AddQuestions < ActiveRecord::Migration
  def change
    create_table :questions do |t|
      t.references :user
      t.string :category
      t.string :content
      t.timestamps
      t.integer :time, default: 450
      t.boolean :resolved, default: false
      t.string :option_a
      t.string :option_b
    end
  end
end
<file_sep>/app/models/question.rb
class Question < ActiveRecord::Base
  has_many :votes
  belongs_to :user

  validates :user_id, presence: true
  validates :category, presence: true
  validates :time, presence: true
  validates :content, presence: true, length: {maximum: 25}
  validates :option_a, presence: true, length: {maximum: 280}
  validates :option_b, presence: true, length: {maximum: 280}

  #validate :tagged_user_is_registered

  def expire_time
    updated_at + time.minutes if time
  end

  def expired?
    time.nil? ? false : expire_time <= Time.now
  end

  def close_expired
    self.update(resolved: true)
  end

  def vote_count(answer)
    votes.where(value: answer).count
  end

  ## CUSTOM VALIDATIONS ##
  #def tagged_user_is_registered
  #  if tagged_user != "" && User.where(username: tagged_user).empty?
  #    errors.add(:tagged_user, "is not a registered user!")
  #  end
  #end
 end
