File: stub_server.rb

package info (click to toggle)
ruby-em-http-request 1.1.2-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 628 kB
  • ctags: 243
  • sloc: ruby: 3,478; makefile: 2
file content (42 lines) | stat: -rw-r--r-- 899 bytes parent folder | download
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
class StubServer
  module Server
    def receive_data(data)
      if echo?
        send_data("HTTP/1.0 200 OK\r\nContent-Length: #{data.bytesize}\r\nContent-Type: text/plain\r\n\r\n")
        send_data(data)
      else
        send_data @response
      end

      close_connection_after_writing
    end

    def echo= flag
      @echo = flag
    end

    def echo?
      !!@echo
    end

    def response=(response)
      @response = response
    end
  end

  def initialize options = {}
    options = {:response => options} if options.kind_of?(String)
    options = {:port     => 8081, :host => '127.0.0.1'}.merge(options)

    host = options[:host]
    port = options[:port]
    @sig = EventMachine::start_server(host, port, Server) do |server|
      server.response = options[:response]
      server.echo     = options[:echo]
    end
  end

  def stop
    EventMachine.stop_server @sig
  end
end