Skip to content
Permalink
Browse files

Guides: Action Request & Response

  • Loading branch information...
jodosha committed May 13, 2015
1 parent a94fe55 commit b629e2551a0d6ba89888f1d0ec5550d2e3c98e2b
Showing with 70 additions and 0 deletions.
  1. +69 −0 source/guides/actions/request-and-response.md
  2. +1 −0 source/layouts/guides.erb
@@ -0,0 +1,69 @@
---
title: Lotus - Guides - Request & Response
---

# 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 a few informations that we can introspect.

```ruby
# apps/web/controllers/dashboard/index.rb
module Web::Controllers::Dashboard
class Index
include Web::Action
def call(params)
puts request.path_info # => "/dashboard"
puts request.request_method # => "GET"
puts request.get? # => true
puts request.post? # => false
puts request.referer # => http://example.com/
puts request.user_agent # => "Mozilla/5.0 Macintosh; ..."
puts request.ip # => "127.0.0.1"
end
end
end
```

<p class="warning">
To instantiate a <code>request</code> for each incoming HTTP request can lead to a minor perf degradation.
As an alternative, please consider to get the same information from private action methods like <code>accepts?</code> or from the raw Rack environment <code>params.env</code>.
</p>

# Response

The implicit return value of `#call` is a serialized `Rack::Response` (see [#finish](http://rubydoc.info/github/rack/rack/master/Rack/Response#finish-instance_method)):

```ruby
# apps/web/controllers/dashboard/index.rb
module Web::Controllers::Dashboard
class Index
include Web::Action
def call(params)
end
end
end
# It will return [200, {}, [""]]
```

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

```ruby
# apps/web/controllers/dashboard/index.rb
module Web::Controllers::Dashboard
class Index
include Web::Action
def call(params)
self.status = 201
self.body = 'Hi!'
self.headers.merge!({ 'X-Custom' => 'OK' })
end
end
end
# It will return [201, { "X-Custom" => "OK" }, ["Hi!"]]
```
@@ -38,6 +38,7 @@
<li><a href="/guides/actions/overview">Overview</a></li>
<li><a href="/guides/actions/basic-usage">Basic Usage</a></li>
<li><a href="/guides/actions/parameters">Parameters</a></li>
<li><a href="/guides/actions/request-and-response">Request & Response</a></li>
</ul>
</li>

0 comments on commit b629e25

Please sign in to comment.
You can’t perform that action at this time.