Introducing the app-routes gem

The app-routes gem makes it easy to add Sinatra-like routes to your Ruby based web server.

require 'socket'
require 'app-routes'

class RWServer

  def initialize()
    super()
    params = {}
    @app = AppRoutes.new(params)
    application(params)
  end

  def start

    server = TCPServer.new('0.0.0.0', 4446)

    while (session = server.accept)

      raw_request = session.gets
      request = raw_request[/.[^\s]+(?= HTTP\/1\.\d)/].strip

      result = @app.run(request)
      result ||= "404: page not found"

      session.print "HTTP/1.1 200/OK\rContent-type: text/plain\r\n\r\n"
      session.print result
      session.close
    end
  end

  private

  # -- start of custom code

  def application(params)

    @app.routes do

      get '/sugar' do 
        'ffff'
      end

      get '/sour' do 
        'gggg'
      end

      get '/hello/:name' do
        'zzzz ... hello ' + params[:name]
      end

      get %r{/hello2/([\w]+)} do
        'ready ' + params[:captures].first
      end
    end

  end

  # -- end of custom code

  def get(arg,&block)
    @app.get(arg, &block)
  end

end

rws = RWServer.new
rws.start


Testing

tested http://localhost:4446    observed
------------
-----------------   --------

/hello/James             zzzz ... hello James
   /sugar                   ffff
   /sinatra                 404: page not found

Resources

Tags:
Source:
0919hrs.txt
Published:
22-02-2012 09:19