Skip to content

Instantly share code, notes, and snippets.

@reyesyang

reyesyang/nancy.rb

Created Dec 1, 2015
Embed
What would you like to do?
Nancy is a Sinatra like micro framework for study base on thoughtbot blog: https://robots.thoughtbot.com/lets-build-a-sinatra
require 'rubygems'
require 'bundler/setup'
require 'rack'
require 'pry'
module Nancy
METHODS = %w(get post put patch delete head)
class Base
def initialize
@routes = {}
end
attr_reader :routes, :request
METHODS.each do |method|
define_method(method) do |path, &handler|
route(method.upcase, path, &handler)
end
end
def params
request.params
end
def call(env)
@request = Rack::Request.new env
verb = @request.request_method
requested_path = @request.path_info
if (handlers = @routes[verb]) && (handler = handlers[requested_path])
result = instance_eval &handler
if result.class == String
[200, {}, [result]]
else
result
end
else
[404, {}, ["Oops! No route for #{verb} #{requested_path}"]]
end
end
private
def route(verb, path, &handler)
@routes[verb] ||= {}
@routes[verb][path] = handler
end
end
Application = Base.new
module Delegator
def self.delegate(*methods, to:)
methods.each do |method|
define_method(method) do |*args, &block|
to.send(method, *args, &block)
end
private method
end
end
delegate *METHODS, to: Application
end
end
# # nancy = Nancy::Application
#
# nancy.get '/' do
# [200, {}, ["Your params are #{params.inspect}"]]
# end
#
# nancy.post '/' do
# [200, {}, request.body]
# end
#
# nancy.get '/hello' do
# 'hello from nancy'
# end
include Nancy::Delegator
post '/' do
request.body.read
end
Rack::Handler::WEBrick.run Nancy::Application, Port: 9292
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment