Skip to content

Instantly share code, notes, and snippets.

@EvilScott
Created April 25, 2012 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvilScott/2493092 to your computer and use it in GitHub Desktop.
Save EvilScott/2493092 to your computer and use it in GitHub Desktop.
Guessing game fun using sessions with Sinatra
require 'sinatra'
require 'haml'
require 'json'
enable :sessions
get '/' do
session[:answer] = %w[A B C D].sample
haml :index
end
get '/guess/:value' do
content_type :json
old_answer = session[:answer]
session[:answer] = %w[A B C D].sample
if params[:value] == old_answer
{ :message => 'Correct answer!' }.to_json
else
{ :message => "Wrong answer! It was #{old_answer}!" }.to_json
end
end
__END__
@@index
!!!
%html
%head
%title Session Fun!
%script{ :type => 'text/javascript', :src => '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' }
:javascript
$(document).ready(function(){
$('li.guess').each(function(i, elem){
var elem = $(elem);
elem.click(function(){
console.log('/guess/' + elem.html());
$.get('/guess/' + elem.html(), function(result){
alert(result.message);
});
});
});
});
:css
html, body {
background: #CCCCCC;
}
.main {
width: 200px;
height: 200px;
margin: 75px auto 0;
padding: 20px;
background: white;
border: 1px solid #DDDDDD;
}
h2 {
text-align: center;
}
ul {
list-style-type: none;
}
li.guess {
font-size: 20px;
cursor: pointer;
margin-bottom: 10px;
color: #3300FF;
text-decoration: underline;
}
%body
.main
%h2 Guess the letter!
%ul
%li.guess My guess is A!
%li.guess I'll try B.
%li.guess Maybe C?
%li.guess It's gotta be D...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment