{"id":817,"date":"2010-03-10T16:03:05","date_gmt":"2010-03-10T19:03:05","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=817"},"modified":"2010-04-22T14:55:40","modified_gmt":"2010-04-22T17:55:40","slug":"show-your-objects-baby","status":"publish","type":"post","link":"https:\/\/blog.plataformatec.com.br\/2010\/03\/show-your-objects-baby\/","title":{"rendered":"Show your objects baby!"},"content":{"rendered":"

We have been having some projects lately that needed a lot of admin CRUDs and pages showing a list of attributes, and we were getting bored of copy and paste code like this in our show pages, for every single attribute:<\/p>\n

\r\n

\r\n Name<\/strong>
\r\n <%= @person.name %>\r\n<\/p>\r\n<\/pre>\n

We had already created some helper to do the work for us, but having this helper being copied from one project to another wasn’t that DRY. That’s when we decided to create ShowFor<\/a>.<\/p>\n

ShowFor<\/a> is a DSL to help you showing a list of attributes, with I18n, perfect for show pages in CRUD interfaces. It allows you to replace code\/html duplication in your views using a nice syntax. Let’s see what we can do.<\/p>\n

Attributes<\/h3>\n

Let’s imagine we have a Person model, which has first_name, last_name, age, photo, and confirmed attributes. The following lines show a list of values for a specific person:<\/p>\n

\r\n<% show_for @person do |p| %>\r\n  <%= p.attribute :first_name %>\r\n  <%= p.attribute :last_name %>\r\n  <%= p.attribute :confirmed? %>\r\n  <%= p.attribute :created_at, :format => :short %>\r\n  <%= p.attribute :age, :if_blank => \"No age\" %>\r\n\r\n  <% p.attribute :photo do %>\r\n    <%= image_tag(@person.photo_url) %>\r\n  <% end %>\r\n<% end %>\r\n<\/pre>\n

Here is an example output you will get:<\/p>\n

\r\n
\r\n

First name<\/strong>
Carlos<\/p>\r\n

Last name<\/strong>
Antonio<\/p>\r\n

Confirmed?<\/strong>
Yes<\/p>\r\n

Created at<\/strong>
08 Mar 11:30<\/p>\r\n

Age<\/strong>
24<\/p>\r\n

Photo<\/strong>
\r\n \"Rails\"\r\n <\/p>\r\n<\/div>\r\n<\/pre>\n

As you can see, you are going to get a default html markup, with classes and ids to help you design with CSS. And if you noticed, we are using extra options in some attributes, lets take a look at some of them:<\/p>\n