Module: HttpSimulator

Defined in:
lib/http_sim.rb

Constant Summary collapse

@@erb_files =
{
  index: self.read_file('lib/index.html.erb'),
  request: self.read_file('lib/request.html.erb'),
  response: self.read_file('lib/response.html.erb')
}
@@endpoints =
[]

Class Method Summary collapse

Class Method Details

.read_file(path) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/http_sim.rb', line 25

def self.read_file(path)
  lines = []
  File.open(path, 'r') do |f|
    f.each_line do |line|
      lines.push line
    end
  end
  lines.join
end

.register_endpoint(method, path, default_response) ⇒ Object



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
# File 'lib/http_sim.rb', line 54

def self.register_endpoint(method, path, default_response)
  raise '/ is a reserved path' if path == '/'

  endpoint = Endpoint.new(method, path, default_response)
  @@endpoints.push endpoint

  case endpoint.method
    when 'GET'
      Sinatra::Base.get endpoint.path do
        endpoint.add_request request.body.read
        endpoint.default_response
      end
    when 'PUT'
      Sinatra::Base.put endpoint.path do
        endpoint.add_request request.body.read
        endpoint.default_response
      end
    when 'PATCH'
      Sinatra::Base.patch endpoint.path do
        endpoint.add_request request.body.read
        endpoint.default_response
      end
    when 'POST'
      Sinatra::Base.post endpoint.path do
        endpoint.add_request request.body.read
        endpoint.default_response
      end
    when 'DELETE'
      Sinatra::Base.delete endpoint.path do
        endpoint.add_request request.body.read
        endpoint.default_response
      end
  end

  Sinatra::Base.get "#{endpoint.path}/response" do
    ERB.new(@@erb_files[:response]).result binding
  end

  Sinatra::Base.put "#{endpoint.path}/response" do
    endpoint.response = request.body.read
  end

  Sinatra::Base.delete "#{endpoint.path}/response" do
    endpoint.response = endpoint.default_response
  end

  Sinatra::Base.get "#{endpoint.path}/requests" do
    ERB.new(@@erb_files[:request]).result binding
  end

  Sinatra::Base.delete "#{endpoint.path}/requests" do
    endpoint.requests = []
  end
end

.run!(port: 4567) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/http_sim.rb', line 42

def self.run!(port: 4567)
  Sinatra::Base.get '/' do
    ERB.new(@@erb_files[:index]).result binding
  end

  Class.new(Sinatra::Base) {
    set :port, port

    include HttpSimulator
  }.run!
end