forked from bastelfreak/http2jsonfile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rb
More file actions
43 lines (36 loc) · 979 Bytes
/
Copy pathmain.rb
File metadata and controls
43 lines (36 loc) · 979 Bytes
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
# frozen_string_literal: true
# sinatra.rb
require 'sinatra'
require 'json'
get '/json' do
return 200, JSON.pretty_generate(get_hashtags)
end
post '/json' do
body = JSON.parse(request.body.read)
hashtags = body['hashtags']
write_hashtags(hashtags) if hashtags
return 200, JSON.pretty_generate(get_hashtags)
end
delete '/json' do
File.rename 'hashtags.json', "hashtags.#{Time.new}.json"
file = File.open('hashtags.json', 'w')
file.close
return 200, JSON.pretty_generate(get_hashtags)
end
def write_hashtag(hashtag)
all_hashtags = get_hashtags
all_hashtags['hashtags'] << hashtag
all_hashtags['hashtags'].uniq!
file = File.open('hashtags.json', 'w+')
puts all_hashtags
file.write(JSON.pretty_generate(all_hashtags))
file.close
end
def write_hashtags(hashtags)
hashtags.each do |hashtag|
write_hashtag(hashtag)
end
end
def get_hashtags
File.exist?('hashtags.json') ? JSON.parse(File.read('hashtags.json')) : { 'hashtags' => [] }
end