-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
63 lines (51 loc) · 1.4 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
# First run "bundle install" (remember to "gem install bundler" before).
# Then run by running "ruby app.rb"
require 'sinatra'
require 'fileutils'
FILENAME = "hello.txt"
# Show contents of our file.
get '/hello' do
# a w r
file = File.open(FILENAME, "r") # Open for read
value = file.read
file.close
value
end
# Add more content
post '/hello' do
file = File.open(FILENAME, "w+") # Open for write. Rewrites the content of the file.
file.write(params["name"])
file.close
return 200
end
# Edit the content
put '/hello' do
# old_name => new_name
old_name = params['old_name']
new_name = params['new_name']
file = File.open(FILENAME, "r") # Open for append. Adds content to the file.
contents = file.read
new_contents = contents.gsub(old_name, new_name)
file.close
file = File.open(FILENAME, "w")
file.write(new_contents)
file.close
return 200
end
# Delete file
delete '/hello' do
old_name = params['name']
file = File.open(FILENAME, "r") # Open for append. Adds content to the file.
contents = file.read
new_contents = contents.gsub(old_name, '')
file.close
file = File.open(FILENAME, "w")
file.write(new_contents)
file.close
return 200
end
# COMMANDS:
# curl -XGET "http://localhost:4567/hello"
# curl -XPOST "http://localhost:4567/hello" -d "name"="fernando"
# curl -XPUT "http://localhost:4567/hello" -d "name"="fernando"
# curl -XDELETE "http://localhost:4567/hello"