Request

In order to access the metadata coming from a HTTP request, an action has a private object request that derives from Rack::Request. Here an example of some information that we can introspect.

  1. # apps/web/controllers/dashboard/index.rb
  2. module Web
  3. module Controllers
  4. module Dashboard
  5. class Index
  6. include Web::Action
  7. def call(params)
  8. puts request.path_info # => "/dashboard"
  9. puts request.request_method # => "GET"
  10. puts request.get? # => true
  11. puts request.post? # => false
  12. puts request.xhr? # => false
  13. puts request.referer # => "http://example.com/"
  14. puts request.user_agent # => "Mozilla/5.0 Macintosh; ..."
  15. puts request.ip # => "127.0.0.1"
  16. puts request.env['HTTP_AUTHORIZATION'] # => "Basic abc123"
  17. end
  18. end
  19. end
  20. end
  21. end

Instantiating a request for each incoming HTTP request can lead to minor performance degradation. As an alternative, please consider getting the same information from private action methods like accept? or from the raw Rack environment params.env.

Response

The implicit return value of #call is a serialized Rack::Response (see #finish):

  1. # apps/web/controllers/dashboard/index.rb
  2. module Web
  3. module Controllers
  4. module Dashboard
  5. class Index
  6. include Web::Action
  7. def call(params)
  8. end
  9. end
  10. end
  11. end
  12. end
  13. # It will return [200, {}, [""]]

It has private accessors to explicitly set status, headers and body:

  1. # apps/web/controllers/dashboard/index.rb
  2. module Web
  3. module Controllers
  4. module Dashboard
  5. class Index
  6. include Web::Action
  7. def call(params)
  8. self.status = 201
  9. self.body = 'Your resource has been created'
  10. self.headers.merge!({ 'X-Custom' => 'OK' })
  11. end
  12. end
  13. end
  14. end
  15. end
  16. # It will return [201, { "X-Custom" => "OK" }, ["Your resource has been created"]]

As shortcut we can use #status.

  1. # apps/web/controllers/dashboard/index.rb
  2. module Web
  3. module Controllers
  4. module Dashboard
  5. class Index
  6. include Web::Action
  7. def call(params)
  8. status 201, "Your resource has been created"
  9. end
  10. end
  11. end
  12. end
  13. end
  14. # It will return [201, {}, ["Your resource has been created"]]