forked from copycopter/copycopter-ruby-client
/
fake_copycopter_app.rb
136 lines (111 loc) · 2.85 KB
/
fake_copycopter_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
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
130
131
132
133
134
135
require 'sinatra/base'
require 'json'
require 'thin'
class FakeCopycopterApp < Sinatra::Base
def self.start
Thread.new do
Thin::Logging.silent = true
Rack::Handler::Thin.run(self, :Port => port)
end
end
def self.port
(ENV['COPYCOPTER_PORT'] || 3002).to_i
end
def self.add_project(api_key)
Project.create(api_key)
end
def self.reset
Project.delete_all
end
def self.project(api_key)
Project.find(api_key)
end
def with_project(api_key)
if api_key == 'raise_error'
halt 500, { :error => "Blah ha" }.to_json
elsif project = Project.find(api_key)
yield(project)
else
halt 404, { :error => "No such project" }.to_json
end
end
get "/api/v2/projects/:api_key/published_blurbs" do |api_key|
with_project(api_key) { |project| project.published.to_json }
end
get "/api/v2/projects/:api_key/draft_blurbs" do |api_key|
with_project(api_key) { |project| project.draft.to_json }
end
post "/api/v2/projects/:api_key/draft_blurbs" do |api_key|
with_project(api_key) do |project|
data = JSON.parse(request.body.read)
project.update('draft' => data)
201
end
end
post "/api/v2/projects/:api_key/deploys" do |api_key|
with_project(api_key) do |project|
project.deploy
201
end
end
class Project
attr_reader :draft, :published, :api_key
def initialize(attrs)
@api_key = attrs['api_key']
@draft = attrs['draft'] || {}
@published = attrs['published'] || {}
end
def to_hash
{ 'api_key' => @api_key,
'draft' => @draft,
'published' => @published }
end
def update(attrs)
@draft. update(attrs['draft']) if attrs['draft']
@published.update(attrs['published']) if attrs['published']
self.class.save(self)
end
def reload
self.class.find(api_key)
end
def deploy
@published.update(@draft)
self.class.save(self)
end
def self.create(api_key)
project = Project.new('api_key' => api_key)
save(project)
project
end
def self.find(api_key)
open_project_data do |data|
if project_hash = data[api_key]
Project.new(project_hash.dup)
else
nil
end
end
end
def self.delete_all
open_project_data do |data|
data.clear
end
end
def self.save(project)
open_project_data do |data|
data[project.api_key] = project.to_hash
end
end
def self.open_project_data
project_file = File.expand_path('/../../../tmp/projects.json', __FILE__)
if File.exist?(project_file)
data = JSON.parse(IO.read(project_file))
else
data = {}
end
result = yield(data)
File.open(project_file, "w") { |file| file.write(data.to_json) }
result
end
end
end