CLICK THAT BUTTON

Language: Ruby

# The Sinatra app behind http://clickthatbutton.com/ running on http://heroku.com

# I can't figure out how to increment the "clicks" counter and get the db to return 
# the new total without doing another request... holler if you know how...
# I tried to use Sequel and ended up getting pissed off somehow, so reverted to
# using Active Record and laying in the hammock.

require 'rubygems'
require 'sinatra'
require 'erb'
require 'active_record'

dbconfig = YAML.load(File.read('config/database.yml'))
ActiveRecord::Base.establish_connection dbconfig['production']

class CreateClicks < ActiveRecord::Migration
  def self.up
    create_table :clicks do |t|
      t.integer :clicks, :default => 0, :null => false
    end
    Click.create!(:clicks => 0)
  end
end

class Click < ActiveRecord::Base
end

get '/' do
  response.set_cookie('click', 0) if request.cookies['click'].nil?
  @clicks_total = Click.first.clicks
  erb :index
end

post '/' do
  Click.first.increment!(:clicks)
  Click.first.clicks.to_s
end
Reveal More
Added almost 2 years ago by Costco_normal trevorturk