
I need to get a request uuid or time when server get a request. It's easy in Rails, but I'm working on a gem and I would like it to be more generic. So I would like it to work also with Sinatra and every other Ruby application which works in a http server.
This is another problem, it's a gem. I can't put Time.now
at the beggining of my application controller. I need it to be generic, so it should work with different frameworks.
What would you propose?
1 Answer
You can implement a Rack middleware which you can use independently from your actual application framework (as long as it used rack, which is true for at least Rails, Sinatra, Padriono and most other Ruby web frameworks).
Rails already includes a middleware for adding a unique ID to a request of required in ActionDispatch::RequestId. Another alternative could be the rack-request-id gem.
A minimal versions of this midleware could look like this:
class RequestIdMiddleware def initialize(app) @app = app end def call(env) env['request_id'] = env['HTTP_X_REQUEST_ID'] || SecureRandom.uuid env['request_started_at'] = Time.now @app.call(env) end end
You can then use this middleware in your config.ru
or by adding this to your application.rb
in Rails:
config.middleware.use RequestIdMiddleware
2ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoaWxuZWaBcn2OoautqF2nsrLBxKyrZq2lnrFuu9FmqZ6ppZrAtXnSrZirrF2ptq6xjKKlZqqll8Zurc%2Bpo6Kbkam2sLrS