Last Update: 2019-03-20 16:06:20 -0700


Forme is a HTML forms library for ruby with the following goals:

  1. Have no external dependencies

  2. Have a simple API

  3. Support forms both with and without related objects

  4. Allow compiling down to different types of output


Forme is designed to make creating HTML forms easier. Flexibility and simplicity are primary objectives. The basic usage involves creating a Forme::Form instance, and calling input and tag methods to return html strings for widgets, but it could also be used for serializing to other formats, or even as a DSL for a GUI application.

In order to be flexible, Forme stores tags in abstract form until output is requested. There are two separate abstract forms that Forme uses. One is Forme::Input, and the other is Forme::Tag. Forme::Input is a high level abstract form, while Forme::Tag is a low level abstract form.

The difference between Forme::Input and Forme::Tag is that Forme::Tag directly represents the underlying html tag, containing a type, optional attributes, and children, while the Forme::Input is more abstract and attempts to be user friendly. For example, these both compile by default to the same select tag:

f.input(:select, :options=>[['foo', 1]])
# or
f.tag(:select, {}, [f.tag(:option, {:value=>1}, ['foo'])])

The processing of high level Forme::Inputs into raw html data is broken down to the following steps (called transformers):


converts a Forme::Input instance into a Forme::Tag instance (or array of them).


If the Forme::Input instance has a error, takes the formatted tag and marks it as having the error.


If the Forme::Input instance has any help text, adds the help text in a separate tag.


If the Forme::Input instance has a label, takes the formatted output and labels it.


Takes the output of the formatter, labeler, and error_handler transformers, and wraps it in another tag (or just returns it unmodified).


converts a Forme::Tag instance into an html string.

Technically, only the Serializer is necessary. The Forme::Form#input and Forme::Form#tag methods return Input and Tag objects. These objects both have to_s defined to call the appropriate Serializer with themselves. The Serializer calls the appropriate Formatter if it encounters an Input instance, and attempts to serialize the output of that (which is usually a Tag instance). It is up to the Formatter to call the Labeler, ErrorHandler, Helper, and/or Wrapper.

The Forme::Form object takes the 6 transformers as options (:formatter, :labeler, :error_handler, :helper, :wrapper, :inputs_wrapper, and :serializer), all of which should be objects responding to call (so you can use +Proc+s) or be symbols registered with the library using Forme.register_transformer:

Forme.register_transformer(:wrapper, :p) do |tag, input|
  input.tag(:p, {}, tag)

Most transformers are called with two arguments, tag and input. tag is a Forme::Tag instance, and input is a Forme::Input instance. The Formatter and Serializer transformers are the two exceptions, with Formatter being called with just an input, and Serializer potentionally being called with any object. The Serializer will in general recursively call itself with children of the argument given.

There is also an InputsWrapper transformer, that is called by Forme::Form#inputs. It's used to wrap up a group of related options (in a fieldset by default). It takes form (Forme::Form instance) and input_opts (Hash) arguments.

Most of the transformers can be overridden on a per instance basis by passing the appropriate option to input or inputs:

f.input(:name, :wrapper=>:p)

Existing transformers can be easily extended (ie, to set the class attribute), by creating your own transformer and then calling the existing transformer.

Forme.register_transformer(:labeler, :explicit) do |tag, input|
  input.opts[:label_attr] ||= { :class => 'label' }, input)


gem install forme


Demo Site




Google Group!forum/ruby-forme

Bug Tracker

Basic Usage

Without an object, Forme is a simple form builder:

f =>'/foo', :method=>:post) # '<form action="/foo" method="post">'
f.input(:textarea, :value=>'foo', :name=>'bar') # '<textarea name="bar">foo</textarea>'
f.input(:text, :value=>'foo', :name=>'bar') # '<input name="bar" type="text" value="foo"/>'
f.close # '</form>'

With an object, Form#input calls forme_input on the obj with the form, field, and options, which should return a Forme::Input or Forme::Tag instance. Also, in Form#initialize, forme_config is called on object with the form if the object responds to it, allowing customization of the entire form based on the object.

f =
f.input(:field) # '<input id="obj_field" name="obj[field]" type="text" value="foo"/>'

If the object doesn't respond to forme_input, it falls back to creating text fields with the name and id set to the field name and the value set by calling the given method on the object (or using [] if the object is a hash).

f =[:foo])
f.input(:first) # '<input id="first" name="first" type="text" value="foo"/>'


Forme comes with a DSL:

Forme.form(:action=>'/foo') do |f|
  f.input(:text, :name=>'bar')
  f.tag(:fieldset) do
    f.input(:textarea, :name=>'baz')
# <form action="/foo">
#   <input name="bar" type="text"/>
#   <fieldset>
#     <textarea name="baz"></textarea>
#   </fieldset>
#   <input type="submit" value="Update"/>
# </form>

You can wrap up multiple inputs with the :inputs method:

Forme.form(:action=>'/foo') do |f|
  f.inputs([[:text, {:name=>'bar'}], [:textarea, {:name=>'baz'}]])
# <form action="/foo">
#   <fieldset class="inputs">
#     <input name="bar" type="text"/>
#     <textarea name="baz"></textarea>
#   </fieldset>
# </form>

You can even do everything in a single method call:

  :inputs=>[[:text, {:name=>'bar'}], [:textarea, {:name=>'baz'}]])

Forme::Form Creation

As shown above, the general way to create Forme::Form instances is via the Forme.form method. This method takes up to 3 arguments, and yields the Forme::Form object to the block (if given). Here are the argument styles that you can use for Forme.form.

No args

Creates a Form object with no options and not associated to an obj, and with no attributes in the opening tag.

1 hash arg

Treated as opening form tag attributes, creating a Form object with no options.

1 non-hash arg

Treated as the Form's obj, with empty options and no attributes in the opening tag.

2 hash args

First hash is opening attributes, second hash is Form options.

1 non-hash arg, 1-2 hash args

First argument is Form's obj, second is opening attributes, third if provided is Form's options.


# No arguments

# 1 hash argument (attributes)

# 1 non-hash argument (a reference object used when building the form)

# 2 hash arguments (attributes, and options)
Forme.form({:action=>'/foo'}, :values=>params)

# 1 non-hash argument, 1-2 hash arguments (ref obj, attributes, options)
Forme.form(Album[1], :action=>'/foo')
Forme.form(Album[1], {:action=>'/foo'}, :values=>params)

If you want a Forme::Form instance where the reference object is a Hash, then you need to pass the hash object using the :obj option:

Forme.form({:action=>'/foo'}, :obj=>{:foo=>'bar'})

You can also create Forme::Form objects the normal ruby way using Forme::Form#new. The difference between Forme::Form#new and Forme.form is that Forme.form includes the enclosing <form> tag, where Forme::Form#new does not. Because of this, Forme::Form does not accept a hash of <form> tag attributes, so it has the following API:

# No arguments

# 1 hash argument>params)

# 1 non-hash argument[1])

# 1 non-hash argument, 1-2 hash arguments[1], :values=>params)

Forme::Form Methods


If you create a Form via Forme::Forme#new, you can use the form method to create a form tag:

f =

This is what Forme.form uses internally to create the <form> tag


This adds an input to the form. If the form has an associated object, and that object responds to forme_input, calls forme_input with the argument and options:

f =
f.input(:field) # '<input id="obj_field" name="obj[field]" type="text" value="foo"/>'

If the form has an associated object, and that object does not respond to forme_input, calls the method on the object (or uses [] if the object is a hash), and uses the result as the value for a text input:

f =[:foo])
f.input(:first) # '<input id="first" name="first" type="text" value="foo"/>'

If the object does not respond to forme_input, you can change the type of the input via the :type option:

f =
f.input(:field, :type=>:email) # '<input id="obj_field" name="obj[field]" type="email" value="foo"/>'

If the form does not have an associated object, the first argument is used as the input type:

f =
f.input(:text) # '<input type="text" />'

The second argument is an options hash. See below for the supported input types and options.


This adds a tag to the form. If a block is given, yields to the block, and tags and inputs inside the block are placed inside the tag. The first argument is the type of tag to create, and the second argument if given should be a hash of tag attributes. This allows you to nest inputs inside tags:

Forme.form do |f|
  f.tag(:span, :class=>"foo") do

Which results in a form similar to the following:

  <span class="foo">
    <input type="text"/>


This wraps multiple inputs in a tag (it uses the inputs_wrapper transformer discussed below, so it uses a fieldset by default). You can give the inputs to add as an enumerable argument:

f.inputs([:textarea, [:text, :value=>'a']])
# <fieldset>
#   <textarea></textarea>
#   <input type="text" value="a"/>
# </fieldset>

You can also provide a block:

f.inputs([:textarea]) do
  f.input(:text, :value=>'a')

Any options given are passed to the inputs_wrapper (so you can use options such as :legend to set a legend for the fieldset), and also to the the with_opts (so you can use options such as :wrapper to modify the default wrapper transformer for inputs inside the block). There is also one option specific to the inputs method:


Sets the default inputs_wrapper to use for calls to inputs inside the block. The reason for this option is that :inputs_wrapper option affects the current call to inputs, so if you want to use a different inputs_wrapper for nested calls, you need this option.


This adds a submit input to the form:

# <input type="submit"/>

It can be called with a string to provide a value for the button:

# <input type="submit" value="Search"/>

It can be called with a hash to provide options for the submit input:

f.button(:value=>'Search', :class=>'btn')
# <input class="btn" type="submit" value="Search"/>


This requires a block, and modifies the Form's options inside the block, restoring the options when the block returns:

# <input type="text"/>
f.with_opts(:wrapper=>:li) do
# <li><input type="text"/></li>

This supports most options you can provide to the Form, but not all.


This uses with_opts to change the Form's object temporarily, but it yields the object to the block, and also supports appending to the existing namespaces:

Forme.form([:foo], :namespace=>'a') do |f|
  # <input id="a_first" name="a[first]" type="text" value="foo"/>
  f.with_obj(['foobar'], 'b') do |o|
    f.input(:first, :size=>o.first.size)
    # <input id="a_b_first" name="a[b][first]" size="6" type="text" value="foobar"/>


This allows you to provide an object-yielding enumerable. Forme will call with_obj with each object in the enumerable. It yields each object as well as the index of the object in the enumerable, and includes the index in the namespace:

objectlist = ['foobar', ['good']]
Forme.form([:foo], :namespace=>'a') do |f|
  f.each_obj(objectlist, 'b') do |o, i|
    f.input(:first, :size=>10+i)
  # <input id="a_b_0_first" name="a[b][0][first]" size="10" type="text" value="foobar"/>
  # <input id="a_b_1_first" name="a[b][1][first]" size="11" type="text" value="good"/>

Sequel Support

Forme ships with a Sequel plugin (use Sequel::Model.plugin :forme to enable), that makes Sequel::Model instances support the forme_config and forme_input methods and return customized inputs. An additional instance method, forme_namespace can optionally be defined to customize how model classnames are transformed into form classes and input IDs and names. This can be useful if your Sequel::Model classes are nested under a parent namespace. It falls back to the behaviour of Sequel::Model#underscore.

module Admin
  class Albums < Sequel::Model
    def forme_namespace'/', '_')


The Sequel support handles inputs based on database columns, and automatically handles labels and errors.

Forme.form(Album[1], :action=>'/foo') do |f|
  f.input :name
  f.input :copies_sold

This will create a form similar to:

<form action="/foo" method="post">
  <label>Name: <input id="album_name" name="album[name]" type="text" value="Rising Force"/></label>
  <label>Copies Sold: <input id="album_copies_sold" name="album[copies_sold]" type="number" value="100000"/></label>

The Forme Sequel plugin also integerates with Sequel's validation reflection support with the validation_class_methods plugin that ships with Sequel. It will add pattern and maxlength attributes based on the format, numericality, and length validations.

specialized input options

In addition to the default Forme options, the Sequel support includes, for specific column types, these additional options to the input method:



Can be set to :select, :radio, or :checkbox. :select will use a select input with three options, a blank option, a true option, and a false option. :radio will use two radio inputs, one for true and one for false. :checkbox will use a single checkbox input. By default, uses :select if NULL values are allowed and the option is not required, and :checkbox otherwise.


The value to use for the false label, 'No' by default.


The value to use for the false input, 'f' by default.


The value to use for the true label, 'Yes' by default.


The value to use for the true input, 't' by default.



Can be set to :textarea to use a textarea input. You can use the usual attributes hash or a stylesheet to control the size of the textarea.


The Sequel support also handles associations, allowing you to change which objects are associated to the current object.

Forme.form(Album[1], :action=>'/foo') do |f|
  f.input :name
  f.input :artist
  f.input :tags, :as=>:checkbox

This will create a form similar to:

<form action="/foo" method="post">
  <label>Name: <input id="album_name" name="album[name]" type="text" value="Blue Hawaii"/></label>
  <label>Artist: <select id="album_artist_id" name="album[artist_id]">
    <option selected="selected" value="1">Elvis Presley</option>
    <option value="2">The Beatles</option>
    <option value="3">The Monkeys</option>
  <span class="label">Tags:
    <label><input checked="checked" id="album_tag_pks_1" name="album[tag_pks][]" type="checkbox" value="1"/> Rock and Roll</label>
    <label><input id="album_tag_pks_2" name="album[tag_pks][]" type="checkbox" value="2"/> Blues</label>
    <label><input id="album_tag_pks_3" name="album[tag_pks][]" type="checkbox" value="3"/> Country</label>

For one_to_many and many_to_many associations, you will probably want to use the association_pks plugin that ships with Sequel.

This also supports the pg_array_to_many association type that comes with Sequel's pg_array_association plugin.

association input options:


For many_to_one associations, set to :radio to use a series of radio buttons instead a select input. For one_to_many, many_to_many, and pg_array_to_many associations, set to :checkbox to use a series of checkboxes instead of a multiple select input.


If a Dataset, uses the dataset to retrieve the options. If a Proc or Method, calls the proc or method with the default dataset, and should return a modified dataset to use.


Specify the options to use for the input(s), instead of querying the database.


If a String or Symbol, treats it as a method name and calls it on each object returned by the dataset to get the text to use for the option. If not given, tries the following method names in order: :forme_name, :name, :title, :number. If given and not a String or Symbol, a callable object is assumed, and the value is called with each object and should return the text to use for the option.


The Sequel support includes a method called subform, which can handle nested_attributes:

Forme.form(Album[1], :action=>'/foo') do |f|

  f.input :name

  f.subform :artist do
    f.input :name

  f.subform :tracks do
    f.input :number
    f.input :name


This adds an input for editing the artist's name after the album's inputs, as well as inputs for editing the number and name for all of the tracks in the album, creating a form similar to:

<form action="/foo" method="post">
  <label>Name: <input id="album_name" name="album[name]" type="text" value="Blue Hawaii"/></label>

  <input id="album_artist_attributes_id" name="album[artist_attributes][id]" type="hidden" value="1"/>
  <fieldset class="inputs"><legend>Artist</legend>
    <label>Name: <input id="album_artist_attributes_name" name="album[artist_attributes][name]" type="text" value="Elvis Presley"/></label>

  <input id="album_tracks_attributes_0_id" name="album[tracks_attributes][0][id]" type="hidden" value="1"/>
  <fieldset class="inputs"><legend>Track #1</legend>
    <label>Number: <input id="album_tracks_attributes_0_number" name="album[tracks_attributes][0][number]" type="number" value="1"/></label>
    <label>Name: <input id="album_tracks_attributes_0_name" name="album[tracks_attributes][0][name]" type="text" value="Blue Hawaii"/></label>
  <input id="album_tracks_attributes_1_id" name="album[tracks_attributes][1][id]" type="hidden" value="2"/>
  <fieldset class="inputs"><legend>Track #2</legend>
    <label>Number: <input id="album_tracks_attributes_1_number" name="album[tracks_attributes][1][number]" type="number" value="2"/></label>
    <label>Name: <input id="album_tracks_attributes_1_name" name="album[tracks_attributes][1][name]" type="text" value="Almost Always True"/></label>


Note: blank lines added for clarity; they would not appear in the actual output

subform options:


Automatically call inputs with the given values. Using this, it is not required to pass a block to the method, though it will still work if you do.


When using the :grid option, this allows you to specify options to pass to the table InputsWrapper.


Overrides the default :legend used (which is based on the association name). You can also use a proc as the value, which will called with each associated object (and the position in the associated object already for *_to_many associations), and should return the legend string to use for that object.


Sets up a table with one row per associated object, and one column per field.


When using the :grid option, override the labels that would be created via the :inputs option. If you are not providing an :inputs option or are using a block with additional inputs, you should specify this option.


Skip adding a hidden primary key field for existing objects.

Handling form submissions

The Sequel forme plugin only handles creating the forms, it does not handle processing input submitted via forms. For a form such as:

Forme.form(Album[1], :action=>'/foo') do |f|
  f.input :name
  f.input :copies_sold

Input of the form will often be submitted as the following parameter hash (this depends on your web framework, but Rack works this way by default):

{'album'=>{'name'=>'Rising Force', 'copies_sold'=>'100000'}}

One way to handle the form submission is to use Sequel::Model#set_fields.

album = Album[1]
album.set_fields(params['album'], %w'name copies_sold')

Note that you have to specify the parameter names again as the second argument to set_fields.

Handling Submitted parameters becomes more complex as your forms become more complex. For example, if you are only displaying certain form fields in certain situations:

album = Album[1]
Forme.form(album, :action=>'/foo') do |f|
  f.input :name
  f.input :copies_sold if album.released?

Then your parameter handling becomes more complex:

album = Album[1]
album.set_fields(params['album'], %w'name')
album.set_fields(params['album'], %w'copies_sold') if album.released?

As you can see, you basically need to recreate the conditionals used when creating the form, so that that the processing of the form submission handles only the inputs that were displayed on the form.

forme_set plugin

The forme_set plugin is designed to make handling form submissions easier. What it does is record the form fields that are used on the object, and then it uses those fields to handle input submitted for the object. For example:

album = Album[1]
Forme.form(album, :action=>'/foo') do |f|
  f.input :name
  f.input :copies_sold if album.released?

If the album has been released, and the form would display the name and copies_sold inputs, then forme_set will accept input for both. If the album has not been released, the form will only display the name input, so forme_set will only accept the name input.

So forme_set offers two advantages over using set_fields:

  1. DRYs up code as you don't have to specify the names twice

  2. Simplifies complex form submissions by eliminating duplication of conditionals


forme_set offers one additional advantage over using set_fields. When dealing with associations, set_fields does not check that the value submitted for an input matches one of the available options displayed on the form. For example, if you have a form such as:

Forme.form(album, :action=>'/foo') do |f|
  f.input :name
  f.input :artist, :dataset=>proc{|ds| ds.where{name > 'M'}}

The form will only display artists whose name is greater than 'M'. However, if you process input using:

album.set_fields(params['album'], %w'name artist_id')

Then a malicious user can submit an artist_id for an artist whose name is not greater than 'M', and the value will be set. In addition to setting values, forme_set also adds validations that the submitted values for associated objects match one of the options displayed on the form, which can increase security.


Because forme_set relies on creating form inputs using the same model instance that will be used for accepting input, using it often requires some code rearranging. If you are storing Forme::Form objects and later using them on forms, it is fairly simple to move the Forme::Forme object creation to a method, that you can call both in the initial display and when processing the input:

def album_form(album)
  Forme.form(album, :action=>'/foo') do |f|
    f.input :name
    f.input :copies_sold

Then when displaying the form:

<%= album_form(Album[1]) %>

and when processing the form's input:

album = Album[1]

However, if you use Forme's ERB/Rails template integration (see below), and are inlining forms in your templates, unless you want to extract the Forme::Form creation to methods, you have to basically rerender the template when processing the input. How you do this is specific to the web framework you are using, but is it similar to:

@album = Album[1]
render :template


forme_set is not perfect, there are ways to use Forme that forme_set will not handle correctly. First, forme_set only works with forms that use model objects, and doesn't handle inputs where the :obj option is provided to change the input. Additionally, forme_set does not currently handle subform/nested_attributes.

In cases where forme_set does not handle things correctly, you can use forme_parse, which will return metadata that forme_set uses (forme_set calls forme_parse internally). forme_parse returns a hash with the following keys:


A hash of values that can be used to update the model, suitable for passing to Sequel::Model#set.


A hash of values suitable for merging into forme_validations. Used to check that the submitted values for associated objects match one of the options for the input in the form.

It is possible to use forme_set for the values it can handle, and set other fields manually using set_fields.

Other Sequel Plugins

In addition to the Sequel plugins mentioned above, Forme also ships with additional Sequel plugins:


Handles translations for labels using i18n.

Roda Support

Forme ships with two Roda plugins, forme and forme_route_csrf. For new code, it is recommended to use forme_route_csrf, as that uses Roda's route_csrf plugin, which supports more secure request-specific CSRF tokens. In both cases, usage in ERB templates is the same:

<% form(@obj, :action=>'/foo') do |f| %>
  <%= f.input(:field) %>
  <% f.tag(:fieldset) do %>
    <%= f.input(:field_two) %>
  <% end %>
<% end %>

The forme_route_csrf plugin's form method supports the following options in addition to the default Forme.form options:


Set to force whether a CSRF tag should be included. By default, a CSRF tag is included if the form's method is one of the request methods checked by the Roda route_csrf plugin.


Set whether to force the use of a request specific CSRF token. By default, uses a request specific CSRF token unless the Roda route_csrf plugin has been configured to support non-request specific tokens.

The forme plugin does not require any csrf plugin, but will transparently use Rack::Csrf if it is available. If Rack::Csrf is available a CSRF tag if the form's method is POST, with no configuration ability.

Both plugins also support the following option:


The object that the form output should be injected into when injecting output (+@_out_buf+ by default).

Sinatra Support

Forme ships with a ERB extension that you can get by require "forme/erb" and using including Forme::ERB::Helper. This is tested to support ERB templates in Sinatra. It allows you to use the following API in your erb templates:

<% form(@obj, :action=>'/foo') do |f| %>
  <%= f.input(:field) %>
  <% f.tag(:fieldset) do %>
    <%= f.input(:field_two) %>
  <% end %>
<% end %>

In order to this to work transparently, the ERB outvar needs to be @_out_buf. If that is not the case, use the :output option to form to specify the outvar.

Rails Support

Forme ships with a Rails extension that you can get by require "forme/rails" and using helper Forme::Rails::ERB in your controller. If allows you to use the following API in your Rails forms:

<%= forme(@obj, :action=>'/foo') do |f| %>
  <%= f.input(:field) %>
  <%= f.tag(:fieldset) do %>
    <%= f.input(:field_two) %>
  <% end %>
<% end %>

This has been tested on Rails 3.2-5.2.

Input Types and Options

These are the types and options supported by Forme::Input objects, usually created via Forme::Form#input:

General Options

These options are supported by all of the input types:


The attributes hash to use for the given tag, takes precedence over other options that set attributes.


Set the autofocus attribute if true


A class to use. Unlike other options, this is combined with the classes set in the :attr hash.


Automatically replace underscores with hyphens for symbol data attribute names in the :data hash. Defaults to false.


A hash of data-* attributes for the resulting tag. Keys in this hash will have attributes created with data- prepended to the attribute name.


Set the disabled attribute if true


Set an error message, invoking the error_handler


Set a custom error_handler, overriding the form's default


Set a custom helper, overriding the form's default


The id attribute to use


The base to use for the name and id attributes, based on the current namespace for the form.


Set a label, invoking the labeler


Set a custom labeler, overriding the form's default


The name attribute to use


Set the form object, overriding the form's default


The placeholder attribute to use


Set the required attribute if true


Override the type of the input when the form has an associated object but the object does not respond to forme_input


The value attribute to use for input tags, the content of the textarea for textarea tags, or the selected option(s) for select tags.


Set a custom wrapper, overriding the form's default

Input Types


Creates an input tag with type checkbox, as well as a hidden input tag. Options:


Mark the checkbox as checked.


The value to use for the hidden input tag.


Don't create a hidden input tag.


Creates an input tag with type radio. Options:


Mark the radio button as checked.

:date / :datetime

By default, creates an input tag with type date or datetime. With the :as=>:select option, creates multiple select options. Options:


When value is :select, uses 3 or 6 select boxes by default.


The order of select boxes when using :as=>:select. Entries should be a symbol for the select field and string to use a string (:date default: [:year, '-', :month, '-', :day]) (:datetime default: [:year, '-', :month, '-', :day, ' ', :hour, ':', :minute, ':', :second])


The labels to use for the select boxes. Should be a hash keyed by the

symbol used in order.  By default, no labels are used.

The options to use for the select boxes. Should be a hash keyed by the symbol used in order (e.g. {:year=>1970..2020})


Creates a select tag, containing option tags specified by the :options option. Options:


Add a blank option if true. If the value is a string, use it as the text content of the blank option. The default value can be set with Forme.default_add_blank_prompt, and defaults to the empty string.


If :add_blank is set, sets the attributes to use for the blank option.


If :add_blank is set, can be set to :after to add the prompt after the inputs, instead of before (which is the default).


Creates a multiple select box.


An enumerable of pairs with the first element being option group labels or a hash of option group attributes, and values being enumerables of options (as described by :options below). Creates optgroup tags around the appropriate options. This overrides any options specified via :options.


An enumerable of options used for creating option tags. If the :text_method and :value_method are not given and the entry is an array, uses the first entry of the array as the text of the option, and the second entry of the array as the value of the option.


The value that should be selected. Any options that are equal to this value (or included in this value if a multiple select box), are set to selected.


Uses the size attribute on the tag


If set, each entry in the array has this option called on it to get the text of the object.


Same as :selected, but has lower priority.


If set (and :text_method is set), each entry in the array has this method called on it to get the value of the option.


Creates a set of checkbox inputs all using the same name. Supports the same options as the select type, except that the :multiple option is assumed to be true. Also supports the following options:


The wrapper transformer for individual tags in the set


The labeler transformer for individual tags in the set


The attributes to use for labels for individual tags in the set


Creates a set of radio buttons all using the same name. Supports the same options as the :checkboxset type.


Creates a textarea tag. Options:


The number of columns in the text area.


The number of rows in the text area.

all others

Creates an input tag with the given type. This makes it easy to use inputs such as text and password, as well as newer HTML5 inputs such as number or email. Options:


Uses the size attribute on the tag


Use the maxlength attribute on the tag

Form options

These are the options supported by Forme::Form object, mostly used to set the defaults for Inputs created via the form:


The configuration to use, which automatically sets defaults for the transformers to use.


A Hash of errors from a previous form submission, used to set default errors for inputs when the inputs use the :key option.


Sets the default error_handler for the form's inputs


Sets the default helper for the form's inputs


Sets the default formatter for the form's inputs


Sets the hidden tags to automatically add to this form, see below.


Sets the default options for each input type. This should be a hash with input type keys, where the values are the hash of default options to use for the input type.


Sets the default inputs_wrapper for the form


Sets the default labeler for the form's inputs


Sets the default namespace(s) to use for the form. Namespacing will automatically create namespaced name and id attributes for inputs that use the :key option.


Sets the default obj for the form's inputs.


Sets the serializer for the form


The values from a previous form submission, used to set default values for inputs when the inputs use the :key option.


Sets the default wrapper for the form's inputs

For forms created by Forme.form, the following options are supported:


An array of inputs to create inside the form, before yielding to the block.


A button to add to the form, after yielding to the block.


This should be an array, where elements are one of the following types:

String, Array, Forme::Tag

Added directly as a child of the form tag.


Adds a hidden tag for each entry, with keys as the name of the hidden tag and values as the value of the hidden tag.


Will be called with the form tag object, and should return an instance of one of the handled types (or nil to not add a tag).

Basic Design

Internally, Forme builds an abstract syntax tree of objects that represent the form. The abstract syntax tree goes through a series of transformations that convert it from high level abstract forms to low level abstract forms and finally to strings. Here are the main classes used by the library:


main object


high level abstract tag (a single Input could represent a select box with a bunch of options)


low level abstract tag representing an html tag (there would be a separate Tag for each option in a select box)

The group of objects that perform the transformations to the abstract syntax trees are known as transformers. Transformers use a functional style, and all use a call-based API, so you can use a Proc for any custom transformer.

Transformer Types


tags input/tag, returns string


takes input, returns tag


takes tag and input, returns version of tag with errors noted


takes tag and input, returns version of tag with help added


takes tag and input, returns labeled version of tag


takes tag and input, returns wrapped version of tag


takes form, options hash, and block, wrapping block in a tag

The serializer is the base of the transformations. It turns Tag instances into strings. If it comes across an Input, it calls the formatter on the Input to turn it into a Tag, and then serializes that Tag. The formatter first converts the Input to a Tag, and then calls the labeler if the :label option is set, the error_handler if the :error option is set, and the helper if the :help option is set . Finally, it calls the wrapper to wrap the resulting tag before returning it.

The inputs_wrapper is called by Forme::Form#inputs and serves to wrap a bunch of related inputs.

Built-in Transformers

Forme ships with a bunch of built-in transformers that you can use:



returns HTML strings


returns HTML strings, formats dates and times in American format without timezones


returns plain text strings



turns Inputs into Tags


disables all resulting input tags


uses span tags for most values, good for printable versions of forms



designed for usage with :legend labeler, putting error message after legend, adding error for first input in the set


modifies tag to add an error class and adds a span with the error message


default error_handler for checkboxset and radioset inputs, that adds an error to the last input in the set

This supports the following options:


A hash of attributes to use for the span with the error message



adds a span with the help text

This supports the following options:


A hash of attributes to use for the span with the help message



uses implicit labels, where the tag is a child of the label tag


uses explicit labels with the for attribute, where tag is a sibling of the label tag


adds a legend before the tags, mostly useful for accessible checkboxset and radioset inputs


default labeler for checkboxset and radioset inputs that adds a span before the tags

The :default and :explicit labelers respect the following options:


Can be set to :before or :after to place the label before or after the the input.


A hash of attributes to use for the label tag



returns tag without wrapping


wraps tag in div tag


wraps tags in a fieldset, mostly useful for accessible checkboxset and radioset inputs


same as :li, but also sets inputs_wrapper to :fieldset_ol


wraps tag in li tag


same as :li, but also sets inputs_wrapper to :ol


wraps tag in p tag


wraps tag in span tag


same as :trtd, but also sets inputs_wrapper to :table


wraps tag in a td tag


same as :td, but also sets inputs_wrapper to :tr


wraps tag in a tr tag with a td for the label and a td for the tag, useful for lining up inputs with the :explicit labeler without CSS

All of these except for :default respect the following options:


A hash of attributes to use for the wrapping tag.



uses a fieldset to wrap inputs


uses a div tag to wrap inputs


use both a fieldset and an ol tag to wrap inputs


uses an ol tag to wrap inputs, useful with :li wrapper


uses a table tag to wrap inputs, useful with :trtd wrapper


uses a tr tag to wrap inputs, useful with :td wrapper

All of these support the following options:


A hash of attributes to use for the wrapping tag.

The :default, :fieldset_ol, and :table inputs_wrappers support the following options:


A text description for the inputs, using the legend tag for fieldsets and the caption tag for a table.


A hash of attributes for the legend/caption tag.

The :table inputs_wrapper also supports the following options:


An array of labels, used to setup a row of table headers with the labels.


You can associate a group of transformers into a configuration. This allows you to specify a single :config option when creating a Form and have it automatically set all the related transformers.

There are a few configurations supported by default:


All default transformers


fieldset_ol inputs_wrapper, li wrapper, explicit labeler

You can register and use your own configurations easily:

Forme.register_config(:mine, :wrapper=>:li, :inputs_wrapper=>:ol, :serializer=>:html_usa)>:mine)

If you want to, you can base your configuration on an existing configuration:

Forme.register_config(:yours, :base=>:mine, :inputs_wrapper=>:fieldset_ol)

You can mark a configuration as the default using:

Forme.default_config = :mine

Bootstrap 3 Support

Forme ships with support for Bootstrap 3 HTML formatting. This support is shipped in it's own file, so if you don't use it, you don't pay the memory penalty for loading it.

require 'forme/bs3'
Forme.default_config = :bs3

Other Similar Projects

All of these have external dependencies:

  1. Rails built-in helpers

  2. Formtastic

  3. simple_form

  4. padrino-helpers

Forme's DSL draws a lot of inspiration from both Formtastic and simple_form.




Jeremy Evans <>