Let’s say that in the controller I get an array of objects from the database this way:
@statuses = TwitterStatus.find(:all, :order => 'tweet_id DESC', :include => :twitter_user)
Also I have the following loop in the view:
<% unless @statuses.nil? -%> <ol> <% for status in @statuses %> <li><%= h(status.text -%>/li> <% end -%> </ol> <% end -%>
I have a lot more data in my model class (user info, status_id, etc.) that I would like to put in the view.
The problem is that much of this date needs to be change. I need to format the dates a certain way. I would like to insert ‘target=’_blank” into any URLs in the ‘text’ field.
My first though would be to have something like this in the controller:
for status in @statuses status.date = status.date.formatDate status.url = status.date.insertTarget status.user = status.user.doUserstuff #Adding new attribute status.username = status.user.lookupUserName end
This just feels kinda lame to me. But, I can’t think of anything better.
I want to agree with Aram. My Views were littered with formatting code until I started adding model methods that cleaned them up considerably. In my last app it was Names and Times (an employee scheduling application).
And Time was always a pain, time was everywhere in my views(and vital to the app). So everywhere I wanted to display start time, instead of calling the attribute I had stored in the database, I called a custom method
Also as a final note, If you continue formatting time the same way everywhere in your views, you can extend the Time class and make your calls much more succinct. In my initializers folder I added a ”conversions.rb’ file where I added this little line
Now all I do is is call:
to return my frequently used formatted string anywhere in the application. You can have a whole list of your favorite formats to clean up your views and make them more understandable.