Class: DbAgile::Restful::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/dbagile/restful/server.rb

Constant Summary collapse

DEFAULT_RACK_OPTIONS =

Default Rack options for restful server and client

{:Port => 8711, :Host => "127.0.0.1", :AccessLog => []}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(environment, options = DEFAULT_RACK_OPTIONS) ⇒ Server

Creates a server instance



23
24
25
26
27
# File 'lib/dbagile/restful/server.rb', line 23

def initialize(environment, options = DEFAULT_RACK_OPTIONS)
  raise "Environment may not be nil" if environment.nil?
  @environment = environment
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Server options



20
21
22
# File 'lib/dbagile/restful/server.rb', line 20

def options
  @options
end

Instance Method Details

#startObject

Starts the server inside a thread



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/dbagile/restful/server.rb', line 35

def start
  myself, env  = self, @environment
  rack_server  = ::Rack::Handler::default
  rack_app     = ::Rack::Builder.new{ run DbAgile::Restful::Middleware.new(env) }
  thread       = Thread.new(rack_server, rack_app, options.dup){|s,a,o| 
    s.run(a, o){|server| @server = server}
  }
  
  # Wait until the server is loaded
  try, ok, res = 0, false, nil
  begin
    res = Net::HTTP.get(uri)
    ok = true
  rescue Errno::ECONNREFUSED => ex
    sleep 0.3
  end until (ok or (try += 1)>10)
  raise "Unable to connect to server" if try >= 10
  
  @environment.say("Have a look at #{uri}")
  thread
end

#stopObject

Stops the server



58
59
60
61
# File 'lib/dbagile/restful/server.rb', line 58

def stop
  @server.shutdown if @server.respond_to?(:shutdown)
  @server = nil
end

#uriObject

Returns the server uri given by options



30
31
32
# File 'lib/dbagile/restful/server.rb', line 30

def uri
  URI::parse("http://#{options[:Host]}:#{options[:Port]}/")
end