class Rack::SimpleEndpoint
Create simple endpoints with routing rules, similar to Sinatra actions.
Simplest example:
use Rack::SimpleEndpoint, '/ping_monitor' do 'pong' end
The value returned from the block will be written to the response body, so the above example will return “pong” when the request path is /ping_monitor.
HTTP verb requirements can optionally be specified:
use Rack::SimpleEndpoint, '/foo' => :get do 'only GET requests will match' end use Rack::SimpleEndpoint, '/bar' => [:get, :post] do 'only GET and POST requests will match' end
Rack::Request and Rack::Response objects are yielded to block:
use Rack::SimpleEndpoint, '/json' do |req, res| res['Content-Type'] = 'application/json' %({"foo": "#{req[:foo]}"}) end
When path is a Regexp, match data object is yielded as third argument to block
use Rack::SimpleEndpoint, %r{^/(john|paul|george|ringo)} do |req, res, match| "Hello, #{match[1]}" end
A :pass symbol returned from block will not return a response; control will continue down the Rack
stack:
use Rack::SimpleEndpoint, '/api_key' do |req, res| req.env['myapp.user'].authorized? ? '12345' : :pass end # Unauthorized access to /api_key will be handled by PublicApp run PublicApp
Public Class Methods
new(app, arg, &block)
click to toggle source
# File lib/rack/contrib/simple_endpoint.rb 48 def initialize(app, arg, &block) 49 @app = app 50 @path = extract_path(arg) 51 @verbs = extract_verbs(arg) 52 @block = block 53 end
Public Instance Methods
call(env)
click to toggle source
# File lib/rack/contrib/simple_endpoint.rb 55 def call(env) 56 match = match_path(env['PATH_INFO']) 57 if match && valid_method?(env['REQUEST_METHOD']) 58 req, res = Request.new(env), Response.new 59 body = @block.call(req, res, (match unless match == true)) 60 body == :pass ? @app.call(env) : (res.write(body); res.finish) 61 else 62 @app.call(env) 63 end 64 end
Private Instance Methods
extract_path(arg)
click to toggle source
# File lib/rack/contrib/simple_endpoint.rb 67 def extract_path(arg) 68 arg.is_a?(Hash) ? arg.keys.first : arg 69 end
extract_verbs(arg)
click to toggle source
# File lib/rack/contrib/simple_endpoint.rb 71 def extract_verbs(arg) 72 arg.is_a?(Hash) ? [arg.values.first].flatten.map {|verb| verb.to_s.upcase} : [] 73 end
match_path(path)
click to toggle source
# File lib/rack/contrib/simple_endpoint.rb 75 def match_path(path) 76 @path.is_a?(Regexp) ? @path.match(path.to_s) : @path == path.to_s 77 end
valid_method?(method)
click to toggle source
# File lib/rack/contrib/simple_endpoint.rb 79 def valid_method?(method) 80 @verbs.empty? || @verbs.include?(method) 81 end