anildigital / cheatsweets

Its just sweet

This URL has Read+Write access

Anil (author)
Sat Jul 11 11:11:44 -0700 2009
commit  98ef30c864000617d087730be9c4c89da68105fd
tree    094ba256843cf6e25747d0716c00bfbe6183199d
parent  d9cb93fa73fd128dd23a0a7b14d4c604a5a2d20a
cheatsweets / app.rb
100644 76 lines (53 sloc) 1.564 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
require 'rubygems'
require 'sinatra'
require 'builder'
require 'json'
 
$cheats_list = (`cheat sheets`).split("\n")
 
 
get "/" do
 
  cheats_size = $cheats_list.size
  current_cheat = $cheats_list[rand(cheats_size)]
 
  @cookie = request.cookies["last_cheat"]
 
  if current_cheat == @cookie
    redirect "/"
  end
 
  @cheats = (`cheat #{current_cheat}`).split("\n")
 
  # Reset the cookie
  set_cookie("last_cheat", current_cheat)
  erb :index
 
end
 
 
get "/query/:cheat" do
 
  current_cheat = params[:cheat].split(".")[0]
  @cookie = request.cookies["last_cheat"]
 
  if (current_cheat == @cookie) and (current_cheat.nil? or current_cheat == "")
    redirect "/"
  end
 
  @cheats = (`cheat #{current_cheat}`).split("\n")
 
  # Reset the cookie
  set_cookie("last_cheat", current_cheat)
  if params[:cheat].match(/(.xml)$/)
    @cheat_name, @cheat_info = get_cheat_data(@cheats)
    builder :index
  elsif params[:cheat].match(/(.json)$/)
    content_type 'application/json', :charset => 'utf-8'
    @cheat_name, @cheat_info = get_cheat_data(@cheats)
    response_json = {:cheat_name => @cheat_name, :cheat_info => @cheat_info}
    response_json.to_json
  else
    erb :index
  end
 
end
 
 
def get_cheat_data(cheats)
  cheat_name = @cheats[0].gsub(":", "")
  cheats.shift
  cheat_info = cheats.join("<br />")
  return cheat_name, cheat_info
end
 
#Exception handing for production environment
configure :production do
 
  not_found do
    'This is nowhere to be found'
  end
 
  error do
    'Sorry there was a nasty error - ' + request.env['sinatra.error'].name
  end
 
end