Right now, our routes cannot access the incoming request, i.e. the env
hash. It would be really nice if they could use env
to add more dynamic behavior. For example, you could access the cookies and session data in your handlers via the HTTP request.
Let's fix it.
Before reading the next section, can you try implementing this on your own? We have the
env
hash in theapp.rb
. How would you pass it to the handlers?
All we need to do is pass env
to the Router
and then further pass it to the handlers when we call it. Here's the changelog.
# app.rb
response_html = router.build_response(env)
# router.rb
def build_response(env)
path = env['REQUEST_PATH']
handler = @routes[path] || ->(env) { "no route found for #{path}" }
handler.call(env) # pass the env hash to route handler
end
# config/routes.rb
get('/articles/1') do |env|
puts "Path: #{env['REQUEST_PATH']}"
"First Article"
end
If you're curious how the above code works, especially how the handlers remember the env hash, read this: capture variables outside scope.
Now all our route handlers have access to the incoming HTTP request. Later, we'll wrap this env
hash into a dedicated Request
class for exposing a better API, just like the ActionDispatch::Request
class in Rails.