• Complex markup without the need of concatenation
  • Auto-closing HTML5 tags
  • View-local variables
  • HTTP method override (because /PATCH/DELETE HTTP verbs aren’t understood by browsers)
  • Automatic generation of HTML attributes for inputs: id, name, value
  • Overriding automatic HTML attributes
  • Reading values from request params and/or given entities, to autofill value attributes
  • Automatic selection of current value for radio button and select inputs
  • CSRF protection
  • Infinite nested fields
  • ORM-agnostic

Technical notes

This feature has a similar syntax to other Ruby gems with the same purpose, but it has a different usage if compared with Rails or Padrino.

Those frameworks allow a syntax like this:

The code above isn’t a valid ERB template. To make it work, these frameworks use custom ERB handlers and rely on third-party gems for other template engines.

Because we support a lot of template engines, we wanted to keep it simple: use what ERB already offers. That means we can use Slim, HAML, or ERB and keep the same Ruby syntax.

The technical compromise for the principles described above is to use the form builder in a unique output block.

  1. <%=
  2. form_for :book, routes.books_path do
  3. text_field :title
  4. submit 'Create'
  5. end
  6. %>

This will produce

  1. <form action="/books" id="book-form" method="POST">
  2. <input type="hidden" name="_csrf_token" value="0a800d6a8fc3c24e7eca319186beb287689a91c2a719f1cbb411f721cacd79d4">
  3. <input type="text" name="book[title]" id="book-id" value="">
  4. <button type="submit">Create</button>
  5. </form>
  1. module Web
  2. module Views
  3. module Books
  4. class New
  5. include Web::View
  6. def form
  7. form_for :book, routes.books_path do
  8. text_field :title
  9. submit 'Create'
  10. end
  11. end
  12. end
  13. end
  14. end
  1. <%= form %>

Helper Methods

The API is really clean and concise, it doesn’t require concatenation between the returning value of the block (submit) and the previous lines (div).

  1. <form action="/books" id="book-form" method="POST" class="form-horizontal">
  2. <input type="hidden" name="_csrf_token" value="1825a0a7ea92bbe3fd60cc8b6a0ea00ce3c52030afbf4037370d937bc5248acb">
  3. <div>
  4. <label for="book-title">Title</label>
  5. <input type="text" name="book[title]" id="book-title" value="" class="form-control">
  6. </div>
  7. <button type="submit">Create</button>
  8. </form>

Method Override

Browsers don’t understand HTTP methods outside of and POST. On the other hand, Hanami embraces REST conventions, that goes beyond that two verbs. When we specify a method via :method, it adds a special hidden field _method, that’s understood by the application.

  1. <%=
  2. form_for :book, routes.book_path(book.id), method: :put do
  3. text_field :title
  4. submit 'Update'
  5. end
  6. %>
  1. <form action="/books/23" id="book-form" method="POST">
  2. <input type="hidden" name="_method" value="PUT">
  3. <input type="hidden" name="_csrf_token" value="5f1029dd15981648a0882ec52028208410afeaeffbca8f88975ef199e2988ce7">
  4. <input type="text" name="book[title]" id="book-title" value="Test Driven Development">
  5. <button type="submit">Update</button>
  6. </form>

CSRF Protection

Cross Site Request Forgery (CSRF) is one of the most common attacks on the web. Hanami offers a security mechanism based on a technique called: Synchronizer Token Pattern.

When we enable sessions, it uses them to store a random token for each user. Forms are rendered with a special hidden field (_csrf_token) which contains this token.

On form submission, Hanami matches this input with the value from the session. If they match, the request can continue. If not, it resets the session and raises an exception.

Developers can customize attack handling.

  1. <%=
  2. form_for :delivery, routes.deliveries_path do
  3. text_field :customer_name
  4. fields_for :address do
  5. text_field :city
  6. end
  7. submit 'Create'
  8. %>

Nested collections

  1. <%=
  2. form_for :delivery, routes.deliveries_path do
  3. text_field :customer_name
  4. fields_for_collection :addresses do
  5. text_field :street
  6. end
  7. submit 'Create'
  8. end
  9. %>
  1. <form action="/deliveries" method="POST" accept-charset="utf-8" id="delivery-form">
  2. <input type="hidden" name="_csrf_token" value="920cd5bfaecc6e58368950e790f2f7b4e5561eeeab230aa1b7de1b1f40ea7d5d">
  3. <input type="text" name="delivery[customer_name]" id="delivery-customer-name" value="">
  4. <input type="text" name="delivery[addresses][][street]" id="delivery-address-0-street" value="">
  5. <input type="text" name="delivery[addresses][][street]" id="delivery-address-1-street" value="">
  6. <button type="submit">Create</button>

Automatic values

Imagine we want to update data for delivery. We have two objects: delivery and customer, which are plain objects (no ORM involved). They respond to the following methods:

  1. delivery.id # => 1
  2. delivery.code # => 123
  3. customer.name # => "Luca"
  4. customer.address.class # => Address
  5. customer.address.city # => "Rome"

Let’s compose the form.

  1. <%=
  2. form_for :delivery, routes.delivery_path(id: delivery.id), method: :patch, values: {delivery: delivery, customer: customer} do
  3. text_field :code
  4. fields_for :customer do
  5. text_field :name
  6. fields_for :address do
  7. text_field :city
  8. end
  9. end
  10. submit 'Update'
  11. end
  12. %>

Please note the :values option that we pass to #form_for. It maps the name attributes that we have in the form with the objects that we want to use to fill the values. For instance delivery[code] corresponds to delivery.code (123), delivery[customer][address][city] to customer.address.city ("Rome") and so on..

Params are automatically passed to form helpers, to read values and try to autofill fields. If a value is present both in params and explicit values (:values), the first takes precendence. The reason is simple: params sometimes represent a failed form submission attempt.

Imagine the form described above, and that our user enters "foo" as delivery code. This value isn’t acceptable for our model domain rules, so we render again the form, presenting a validation error. Our params are now carrying on the values filled by our user. For instance: params.get('delivery.code') returns "foo".

Here how the form is rendered:

  1. <form action="/deliveries/1" id="delivery-form" method="POST">
  2. <input type="hidden" name="_method" value="PATCH">
  3. <input type="hidden" name="_csrf_token" value="4800d585b3a802682ae92cb72eed1cdd2894da106fb4e9e25f8a262b862c52ce">
  4. <input type="text" name="delivery[code]" id="delivery-code" value="foo">
  5. <input type="text" name="delivery[customer][name]" id="delivery-customer-name" value="Luca">
  6. <input type="text" name="delivery[customer][address][city]" id="delivery-customer-address-city" value="Rome">
  7. </form>