Implementing a View Helper in Ruby on Rails
I keep hearing that we shouldn't have any logic in our views.
Fair enough.
Then what? Good question. I also keep hearing that we should be using helpers.
Roger that.
So...how?
Yesterday I spent quite a bit of time searching for just such a topic. But what should I search for? I won't bore you with the details, but I used several terms. I kept falling back to "view helpers rails" but didn't get much.
As always, Stack Overflow (www.stackoverflow.com) came to the rescue.
Piecing together several posts I was able to come up with some winning syntax. Got a better way? I am not being sarcastic when I say that I'm all ears. For I was really unable to find any good documentation. At all.
First a little background.
The object I'm working with is a ticket. That means I need to place this code in the tickets helper. I'm working in legacy code and so I can't be certain this file is created automatically, but it exists in app/helpers and is named "tickets_helper." I'd suspect this is all by design (naming, location).
The code I was hoping to move out of the view was a simple conditional. If a ticket's alternate phone number field had data in it, I wanted to display this.
Here's what it looked like:
<% if @ticket.ovr_phone.present? %>
<tr>
<td class="panel-table-label">Alternate Site Phone</td>
<td><%= @ticket.ovr_phone %></td>
</tr>
<% end %>
I copied and pasted that code into tickets_helper.rb and got to work. Here's what I came up with:
def display_ovr_phone(ticket)
if ticket.ovr_phone.present?
content_tag(:tr) do
concat content_tag(:td, "Alternate Site Phone", :class => "panel-table-label")
concat content_tag(:td, ticket.ovr_phone)
end
end
end
I then went back into the original view and replaced the previous code with:
<%= display_ovr_phone(@ticket) %>
Mission accomplished! Hopefully you can disassemble the helper code and see how it all happens. These posts helped much and I'm sorry to say the actual Rails documentation did not.
Posts:
- http://stackoverflow.com/questions/1380938/rails-view-helpers-in-helper-file
- http://stackoverflow.com/questions/3561250/using-helpers-in-rails-3-to-output-html
Documentation:
My intent was not to get down on the documentation. Being open source and all, if I don't like it then I should initiate a pull request and attempt to implement my own code.
My frustration lay in not knowing how to put the pieces together. It's still a bit sketchy, actually. But I have this one bit of code licked!
Cheers!
