Sometime ago we were working on a project together with a designer, and that specific application was full of forms, each one having a different layout, but most of them sharing the same features: inline errors, hints, specific label markup for required fields, etc. To start prototyping the application faster, we used the markup the designer created with similar forms, duplicating the code. But we don’t like code duplication, we weren’t feeling comfortable with it. So we decided to move on and create a tool to help us, that should be flexible enough to let us define the markup that fits better for each application, or even no extra markup at all. Here is SimpleForm!
SimpleForm inputs
From the README:
Forms made easy (for Rails)!
SimpleForm aims to be as flexible as possible while helping you with powerful components to create your forms. The basic goal of simple form is to not touch your way of defining the layout, letting you find the better design for your eyes. Good part of the DSL was inherited from Formtastic, which we are thankful for and should make you feel right at home.
As the README says, SimpleForm is a tool to help you build forms easily in Rails. Let’s see some examples:
<%= simple_form_for @user do |f| %> <%= f.input :username, :label => 'Your username please' %> <%= f.input :password, :hint => 'No special characters.' %> <%= f.input :remember_me, :as => :boolean %> <%= f.button :submit %> <% end -%>
There are plenty of things going on here: we create a form using simple_form_for helper, then we use the :input method to create input elements based on column type. For instance, :username will create a default text input, while :password attribute will render an input type password. For the :username attribute, we are specifying a label manually. For :password, the label will be taken from I18n, and we are adding a hint message to the field. For :remember_me, we are explicitly saying to render it as a checkbox, using the :as => :boolean option (that is the default for boolean attributes). Also, there is a button helper that simply delegates to Rails helpers, in this case submit.
The output for a new @user would be:
<form action="/users" class="simple_form user" id="new_user" method="post">
<div class="input string required">
<label class="string required" for="user_username"><abbr title="required">*</abbr> Your username please</label>
<input class="string required" id="user_username" maxlength="255" name="user[username]" size="50" type="text" />
</div>
<div class="input password required">
<label class="password required" for="user_password"><abbr title="required">*</abbr> Password</label>
<input class="password required" id="user_password" name="user[password]" size="30" type="password" />
<span class="hint">No special characters.</span>
</div>
<div class="input boolean optional">
<label class="boolean optional" for="user_remember_me"> Remember me</label>
<input name="user[remember_me]" type="hidden" value="0" />
<input class="boolean optional" id="user_remember_me" name="user[remember_me]" type="checkbox" value="1" />
</div>
<input id="user_submit" name="commit" type="submit" value="Create User" />
</form>You may have noticed there is some additional css classes added to the markup, like string and required. They are added automatically by SimpleForm to help us style and plug some javascript in. There are specific css classes for each available input type. Also, pay some attention to the label: inside it there is an abbr tag with an asterisk (*) showing that the field is required. SimpleForm uses the new validations reflection API from Rails 3 to check if the attribute has the presence validator, and mark the field as required if so. And we are able to say that a field is required or disable the required mark, by passing the option :required => true|false.
Furthermore, there is the hint tag for the :password attribute that SimpleForm creates based on the :hint option we have defined. Also notice that the gem has automatically added a div wrapper to each input, with the same css classes. SimpleForm allows us to configure this wrapper as well, using for instance p instead of div. We are going to see more about configuration later.
SimpleForm is already prepared to generate some of the new HTML 5 input tags, such as email, url and number inputs:
<%= simple_form_for @user do |f| %> <%= f.input :website, :as => :url %> <%= f.input :email %> <%= f.input :age, :hint => "This defaults to 'number' input based on field type" %> <%= f.button :submit %> <% end -%>
Based on the attribute name, SimpleForm will generate url or email input types, and we can always set a specific type with the :as option. Numeric attributes will always be rendered as input type number.
Working with associations
SimpleForm adds a custom and straightforward method to render select tags for associations, called association. For now, consider our User belongs to a Company, and has and belongs to many Roles. Let’s go straight to the example:
<%= simple_form_for @user do |f| %> <%= f.input :name %> <%= f.association :company %> <%= f.association :roles %> <%= f.button :submit %> <% end -%>
It will detect the association type and render a select tag for choosing the company, listing all companies in the database, and another select for roles, with multiple option enabled.
SimpleForm also has some add-ons, letting us render associations as a collection of radios or check boxes. Using the same example:
f.association :company, :as => :radio f.association :roles, :as => :check_boxes
Now we are rendering a collection of radios for choosing the Company, and another collection of check boxes for choosing Roles.
Configuration
SimpleForm lets us do some customizations by running its install generator:
rails generate simple_form:install # Output create config/initializers/simple_form.rb create config/locales/simple_form.en.yml create lib/templates/erb/scaffold/_form.html.erb
As we can see, running this generator will copy an initializer file, responsible for configuring SimpleForm; a locale file, to let us change some I18n messages; and a form template inside our lib dir. This template will be used instead of the default Rails scaffold form template, so it will create our form already using SimpleForm. Easy, right?
Let’s take a look at some configuration options:
- components: defines the components used by the form builder. We can remove any of them, change the order, or add new ones. Defaults to
[ :label, :input, :hint, :error ]. - hint_tag: tag used for hints, defaults to
span. - error_tag: tag used for errors, defaults to
span. - wrapper_tag: tag used as wrapper to all inputs, defaults to
div - label_text: determines how the label text should be generated altogether with the required text. It must be a lambda/proc that receives both label and required texts. Defaults to
"required label".
There are a lot more options available in the initializer file, such as default input size and priority countries for generating country selects. Also, the locale file lets us determine the required text and mark, or even the entire required html tag.
Internationalization
SimpleForm is ready for I18n, supporting labels and hints. In addition, it lets us set different content for each action, new and edit. Here is an example locale file:
en:
simple_form:
labels:
user:
username: 'User name'
password: 'Password'
edit:
username: 'Change user name'
password: 'Change password'
hints:
user:
username: 'User name to sign in.'
password: 'No special characters, please.'
Simple, right? If it does not find any specific translation using I18n for the label, it will fallback to human_attribute_name.
Here we go!
SimpleForm has much more to offer. We would like to invite you to take a better look at the examples and possibilities. Remember, SimpleForm aims to be flexible and powerful to help you easily build forms, without saying how you should create your markup.
Also, feel free to explore the source code and extend SimpleForm even further. Since it’s based on components, creating a new component which moves the current hints to inside the input (using javascript or the new placehoder attribute in HTML 5), should be easy!
It’s worth saying SimpleForm is Rails 3 compatible in the master branch. If you are using Rails 2.3.x, there is a v1.0 branch and version that you might want to take a look.
SimpleForm has been helping us a lot so far, we hope you enjoy it. Moreover, we would like to enjoy other tools that help your productivity day by day, please leave a comment and let us know, we would appreciate a lot!
Tags: form, gems, open source, plugins, rails, rails3, simple_form
Posted in English | View Comments
RailsMetrics is a new Rails engine which stores everything that is happening inside your application in the database, so you can profile each request, besides creating charts, statistics and extract useful information.
I’ve been working on it for the last couple months in parallel with ActiveSupport::Notifications, which is the foundation for RailsMetrics, and it was open sourced today by Engine Yard!
It was a challenging project due to its threaded nature and I will share a couple things I learned during the process in this blog later. For now, you can watch the screencast below to see what it does and how to install it:
As said in the video, getting it released is just the first step and now it’s your turn to fork and improve it by providing a better layout, creating new reports, charts, etc!
In case you are interested here are some screenshots that I tweeted earlier: http://twitpic.com/13e7fn/full and http://twitpic.com/13e7h2/full.
The javascript novell
A week ago I asked what people uses to create charts in Rails so I could evaluate what would be the best library to use in RailsMetrics. There were three types of libraries: server side ones, flash and javascript. Since I don’t want to depend on having neither RMagick nor Flash installed on the developer machine, I chose the javascript kind.
After some research I ended up with three libraries: g.raphael, flot and jqplot.
For RailsMetrics, I chose to use g.raphael since I can easily manipulate the objects it creates and it is the one which looks better (at least imho
). However it has poor documentation and the default charts have poor customization options compared to the other two libraries, so you end up tweaking the chart by hand (which was fine in my experience).
I’m waiting for your pull requests, enjoy!
Tags: charts, gems, javascript, metrics, notifications, rails
Posted in English | View Comments
This weekend during Rails Bugmash I stumbled across some nice posts about Rails 3 generators which motivated me to share them and add some comments!
First, David Trasbo wrote a nice guide about how to make your first Rails 3 generator, it covers up all the basic steps including setting it up in a gem. He also puts the deserved attention into Thor::Actions, which contains most helpers you need in a generator, like copy_file, template, create_file, empty_directory and so on.
On another post, Ben Scofield talks about apply method, which is also in Thor::Actions, and how to use it to dry your application templates.
Wait… so Thor::Actions is used both in generators and in Rails application templates? Exactly, Rails’ new generators unifies both application templates and generators API into one. While Thor::Actions holds basic methods, all Rails specific methods like environment, rakefile, generator are in Rails::Generators::Actions. If you already wrote an application template, you will feel more at home when writing a Rails 3 generator.
Paul Barry talks how easy it’s to customize your scaffold to use Rspec, Haml and Factory Girl instead of Test::Unit, Erb and Fixtures. This all works because scaffold is just a meta generator which provides hooks for template engine, test framework, ORM and so forth. A good way to see the hooks system working is by running script/generate scaffold --help before and after Paul changes, so you can see exactly how generators options update depending on the configuration values you set. While I wrote Rspec generators used in the example, he implemented himself Haml and Factory Girl generators and they can all be used as example if you plan to build your own.
Finally, Zigzag Chen wrote about templates customization and how you can change your scaffold controller to use json instead of the xml format. New generators have source paths, so you can customize them simply by copying files to RAILS_ROOT/lib/templates.
Rails Bugmash was excellent to gather feedback and we also got some tickets on Lighthouse, mainly about how generators help can be improved for people starting with Rails. Many thanks to Rails Bridge and besides the posts linked above, there is a generator guide, which may help you get started and maybe write your own post as well.
Tags: gems, generators, plugins, rails, ruby, thor
Posted in English | View Comments

All
English only
Em português apenas