-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.rb
129 lines (105 loc) · 2.58 KB
/
base.rb
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
########################################################################
#
# Author: Brian Hood
#
# Description: Anagrams
#
# Application: base.rb
#
# Search the Oxford English dictionary for anagrams of words
#
########################################################################
require 'rubygems' if RUBY_VERSION < "1.9"
require 'MonetDB'
require './datalayerlight.rb'
require 'sinatra/base'
require 'pp'
# Yes i monkey patched Sinatra to add a get and post method
class Sinatra::Base
class << self
def getpost(path, opts={}, &block)
get(path, opts, &block)
post(path, opts, &block)
end
end
end
class AnagramsWeb < Sinatra::Base
set :server, :puma
set :logging, :true
def dbdefaults
@hostname = "172.17.0.7"
@username = "monetdb"
@password = "monetdb"
@dbname = "anagrams"
end
def dbconnect
self.dbdefaults
@conn = DatalayerLight.new
@conn.hostname = @hostname
@conn.username = @username
@conn.password = @password
@conn.dbname = @dbname
@conn.autocommit = false
begin
@conn.connect
rescue Errno::ECONNREFUSED
puts "Database not running!"
puts "Bye!"
exit
end
end
def dbclose
if @conn.autocommit == false; @conn.commit; end
@conn.save
@conn.release
@conn.close
end
configure do
enable :session
end
before do
content_type :html
end
set :title, "Anagrams"
set :port, 8080
set :bind, "0.0.0.0"
def query_handler(sql)
begin
res = @conn.query(sql)
return res
rescue Errno::EPIPE
puts "Connection gone away ?" if @debug == true
end
end
def search(anagram)
self.dbconnect
@anagrams, @wordjumble = Hash.new, Hash.new
if @conn.is_connected?
sql = "SELECT word, anagrams FROM \"anagrams\".words WHERE anagrams LIKE '% #{anagram} %' OR word = '#{anagram}';";
res = query_handler(sql)
while row = res.fetch_hash do
@anagrams.update({"#{row["word"]}" => "#{row["anagrams"]}"})
end
sql_wordjumble = "SELECT a.word AS jumble, b.word FROM \"anagrams\".words a JOIN \"anagrams\".wordjumble b ON (a.word_id = b.word_id) WHERE b.word = '#{anagram}';"
res = query_handler(sql_wordjumble)
while row = res.fetch_hash do
@wordjumble.update({"#{row["jumble"]}" => "#{row["word"]}"})
end
end
self.dbclose
end
getpost '/' do
if params[:submit] != nil
search(params[:anagram])
end
erb :base
end
get '/css/screen.css' do
send_file 'css/screen.css', :type => :css
end
get '/sdf' do
200
end
run!
end
AnagramsWeb.new