Skip to content

Commit

Permalink
Guides: explain the differences between #halt and #status=
Browse files Browse the repository at this point in the history
  • Loading branch information
jodosha committed Jul 20, 2016
1 parent 3234108 commit 4f5f071
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 3 deletions.
56 changes: 56 additions & 0 deletions source/guides/actions/control-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,62 @@ module Web::Controllers::Dashboard
end
```

When `#halt` is used, **Hanami** renders a default status page with the HTTP status and the message.

<p><img src="/images/default-template.png" alt="Hanami default template" class="img-responsive"></p>

To customize the UI for the HTTP 404 error, you can use a [custom error page](/guides/views/custom-error-pages).

## HTTP Status

In case you want let the view to handle the error, instead of using `#halt`, you should use `#status=`.

The typical case is a **failed form submission**: we want to return a non-successful HTTP status (`422`) and let the view to render the form again and show the validation errors.

```ruby
# apps/web/controllers/books/create.rb
module Web::Controllers::Books
class Create
include Web::Action

params do
required(:title).filled(:str?)
end

def call(params)
if params.valid?
# persist
else
self.status = 422
end
end
end
end
```

```ruby
# apps/web/views/books/create.rb
module Web::Views::Books
class Create
include Web::View
template 'books/new'
end
end
```

```erb
# apps/web/templates/books/new.html.erb
<%= unless params.valid? %>
<ul>
<% params.errors(full: true).each do |error| %>
<li><%= error %></li>
<% end %>
</ul>
<% end %>
<!-- form goes here -->
```

## Redirect

A special case of control flow management is relative to HTTP redirect.
Expand Down
7 changes: 4 additions & 3 deletions source/guides/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -875,9 +875,8 @@ describe Web::Controllers::Books::Create do
end

it 'sets errors attribute accordingly' do
action.call(params)

refute action.params.valid?
response = action.call(params)
response[0].must_equal 422

action.errors[:book][:title].must_equal ['is missing']
action.errors[:book][:author].must_equal ['is missing']
Expand Down Expand Up @@ -916,6 +915,8 @@ module Web::Controllers::Books
@book = BookRepository.create(Book.new(params[:book]))

redirect_to '/books'
else
self.status = 422
end
end
end
Expand Down
Binary file added source/images/default-template.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 4f5f071

Please sign in to comment.