Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active December 3, 2019 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/f0149a6673b6b7092781db3fe58ee69a to your computer and use it in GitHub Desktop.
Save JoshCheek/f0149a6673b6b7092781db3fe58ee69a to your computer and use it in GitHub Desktop.
Timing Grape API
require 'grape'
require 'logger'
require 'json'
class MyApi < Grape::API
version 'v1', :using => :path
format :json
desc "Returns first / last name"
get '/:first/:last' do
env['controller_time'] = Time.now
{ first_name: params[:first], last_name: params[:last] }
end
end
class Timing
def initialize(app)
@app = app
end
def call(env)
pre = Time.now
status, headers, body = @app.call(env)
if env['controller_time']
controller = env['controller_time']
post = Time.now
into = (controller - pre).round(2)
outof = (post - controller).round(2)
headers['X-Timing'] = "into=#{into.to_s.inspect}s; outof=#{outof.to_s.inspect}s"
end
return status, headers, body
end
end
app = Rack::Builder.new do
use Timing
run MyApi
end
status, headers, body = app.call(
"REQUEST_METHOD" => "GET",
"PATH_INFO" => "/v1/nia/mejia",
"rack.input" => StringIO.new,
)
status # => 200
JSON.parse body.to_enum(:each).to_a.join # => {"first_name"=>"nia", "last_name"=>"mejia"}
headers['X-Timing'] # => "into=\"0.05\"s; outof=\"0.01\"s"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment