views:

98

answers:

3

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.

+2  A: 

You might want to add some instance methods to the TwitterStatus model. For instance:

def formatted_date
  self.date.formatDate
end
Aram Verstegen
+3  A: 

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).

class Employee

 def full_name
  self.first_name + " " + self.last_name
 end

end

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

class Schedule

 def formatted_start_time
  self.start_time.strftime('%I:%M%p')
 end

end

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

Time::DATE_FORMATS.update(:shift => '%I:%M%p')

Now all I do is is call:

time_object.to_s(:shift)

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.

BushyMark
A: 

Responsibility for formatting really belongs to the view.

The "Rails Way" would be to add a helper method to do the formatting.

There is a helper module associated with each controller and also a global ApplicationHelper.

eg if your controller is StatusController

module StatusHelper

  def status_text( status )
    # do all your formatting and HTML escaping here
    ...
  end

end

and in the view

<% unless @statuses.nil? -%>
  <ol>
    <% for status in @statuses %>
      <li><%= status_text(status) -%></li>
    <% end -%>
  </ol>
<% end -%>
Noel Walters