multithreading - Start and call Ruby HTTP server in the same script -


i wonder how start ruby rack application (such sinatra) , call net::http or similar in same script. of couse like...

require 'sinatra/base' require 'net/http'  t = thread.new     class app < sinatra::base         '/'             'hi!'         end     end      app.run! :host => 'localhost', :port => 1234 end  sleep 2  puts net::http.start('localhost', 1234) { |http| http.get('/') }.body  t.join  puts 'bye!' 

...but doesn't feel optimal sleep 2 seconds, waiting thin start. need kind of callback when server has started or have other suggestions?

if @ run! method in sinatra source in base.rb see this:

def run!(options={})   ...   handler.run self, :host => bind, :port => port |server|     [:int, :term].each { |sig| trap(sig) { quit!(server, handler_name) } }     set :running, true   end   ... end 

there no way attach callbacks around here. but! see :running setting changed once server up.

so, simple solution seems to have thread watch app.settings.running in small polling loop (every 500ms or along lines). once running true can safely stuff.


edit: improved version, bit of monkey patching goodness.
adding after_running callback sinatra:

class sinatra::base   # redefine 'running' setting support threaded callback   def self.running=(isup)     metadef(:running, &proc.new{isup})      return if !defined?(after_running)     return if !isup      thread.new       thread.pass       after_running     end   end end  class app < sinatra::base    set :after_running, lambda {     puts "we're up!"     puts net::http.start('localhost', 1234) { |http| http.get('/') }.body     puts "done"   }    '/'     'hi!'   end  end  app.run! :host => "localhost", :port => 1234 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -