class Genesis::Http::Server
Implement an HTTP server using async_sinatra and thin
Public Class Methods
new(app = nil, **kwargs)
click to toggle source
Inject the channel and extended routes
Calls superclass method
# File lib/genesis/protocol/http/server.rb, line 34 def initialize(app = nil, **kwargs) super(app) @channel = kwargs[:channel] || nil @extended_routes = kwargs[:routes] || {} @views = kwargs[:views] || [] initialize_routes end
start_server()
click to toggle source
Block to actually start the server
# File lib/genesis/protocol/http/server.rb, line 18 def self.start_server app = new(channel: @channel, routes: @handle_routes, views: @args[:views] || []) dispatch = Rack::Builder.app do map '/' do run app end end # Enable full request logging with @debug Thin::Logging.trace=true if @args[:debug] # Since Thin is backed by EventMachine's TCPserver anyways, # This is just a TCPServer like any other - running inside the same EventMachine! Thin::Server.new(@port, '0.0.0.0', dispatch).backend.start end
Private Instance Methods
find_template(views, *a, &block)
click to toggle source
Override template search directorys to add spells
Calls superclass method
# File lib/genesis/protocol/http/server.rb, line 66 def find_template(views, *a, &block) Array(@views).each { |v| super(v, *a, &block) } end
handle_exception!(context)
click to toggle source
Needed to properly catch exceptions in async threads
# File lib/genesis/protocol/http/server.rb, line 78 def handle_exception!(context) if context.message == 'Sinatra::NotFound' error_msg = "Resource #{request.path} does not exist" puts error_msg ahalt(404, error_msg) else puts context.message puts context.backtrace.join("\n") ahalt(500, 'Uncaught exception occurred') end end
initialize_routes()
click to toggle source
Register all routes provided
# File lib/genesis/protocol/http/server.rb, line 45 def initialize_routes @extended_routes.each do |verb, matches| matches.each do |match, data| register_route(verb, match, data[:args], data[:block]) end end end
native_async_schedule(&b)
click to toggle source
Define our asynchronous scheduling mechanism, could be anything Chose EM.defer for simplicity This powers our asynchronous requests, and keeps us from blocking the main thread.
# File lib/genesis/protocol/http/server.rb, line 73 def native_async_schedule(&b) EM.defer(&b) end
partial(template, locals = {})
click to toggle source
Enable partial template rendering
# File lib/genesis/protocol/http/server.rb, line 61 def partial(template, locals = {}) erb(template, layout: false, locals: locals) end
register_route(verb, match, opts, block)
click to toggle source
Injects a route into the sinatra class
# File lib/genesis/protocol/http/server.rb, line 54 def register_route(verb, match, opts, block) async_verb = "a#{verb}" # force verb to async verb self.class.send(async_verb, match, opts, &block) end