-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.rb
75 lines (64 loc) · 1.77 KB
/
app.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
require 'erubis'
require 'active_record'
require 'yaml'
require 'json'
# initialize database configuration file
dbconfig = YAML::load(File.open('config/database.yml'))
# establish database connection
ActiveRecord::Base.establish_connection(dbconfig)
#create table
unless ActiveRecord::Base.connection.table_exists? 'users'
ActiveRecord::Migration.class_eval do
create_table :users do |t|
t.string :name
t.string :email
t.string :desc
t.timestamps
end
end
end
class App
# call method, takes a single hash parameter and returns
# an array containing the response status code, HTTP response
# headers and the response body as an array of strings.
def call env
$params = nil
$params = Rack::Utils.parse_nested_query(env["rack.input"].read)
path = env['PATH_INFO']
routes = ['index','new', 'create_user']
action = path.split("/")
if action.size > 0 and routes.include? action[1]
body = User.new.send(action[1])
elsif action.size == 0
body = User.new.send('new')
else
body = 'Page not found'
end
status = 200
header = {"Content-Type" => "text/html"}
[status, header, [body]]
end
end
# User model that inherit ActiveRecored
class User < ActiveRecord::Base
def new
render :file => 'users/new'
end
def index
@users = User.all
render :file => 'users/index'
end
def create_user
User.create(:name => $params['name'], :email => $params['email'], :desc => $params['desc'])
@users = User.all
render :file => 'users/index'
end
def render(option)
@body = render_erb_file('views/' + option[:file] + '.erb')
end
def render_erb_file(file)
input = File.read(file)
eruby = Erubis::Eruby.new(input)
@body = eruby.result(binding())
end
end