0

I'm not asking for code as an answer, rather, a resource or some general guidance.

I have an index page of users. For each user, I check the "friend status" of each user in respect to the current user. As you can imagine, it is a pretty lengthy if and elsif statements in the view page.. which is basically:

<% if current_user %>
    <% if current_user.friend_with? profile.user %>
        <span class="glyphicon glyphicon-user"></span>
    <% elsif current_user.invited_by? profile.user %>
        <%= link_to '.', friendship_path(profile.user), :method => "put", :class => "glyphicon glyphicon-check" %>
    <% elsif current_user.connected_with? profile.user %>
        <span class="glyphicon glyphicon-send" title="Pending approval"></span>
    <% elsif current_user == profile.user %>
        <span class="glyphicon glyphicon-user"></span>
    <% else %>
        <%= link_to '.', friendships_path(:user_id => profile), :method => "post", :class => "glyphicon glyphicon-plus" %>

I have this entire logic in the view page, and it is very cumbersome. I would like to clean it up a little and stash it away in the controller (if advisable).

Any guidance would be really appreciated. I imagine having a method to return the type of icon or to render some kind of html code and pass it into the view. Thanks!!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
dubc15
  • 131
  • 1
  • 10

2 Answers2

0

Helper method is the answer..

Move it in some method in your helper like

def my_awesome_helper_method
- logic -
end

and in the view just call

<%=my_awesome_helper_method %>

much cleaner...!

Manish Puri
  • 422
  • 4
  • 6
  • thank you - what language/syntax do we use to return html code from the generator? for example, within the helper method, i want to return
    , how do i write that up in the controller?
    – dubc15 May 28 '15 at 21:33
  • you can either use content_tag or return it as string and use a htmlsafe – Manish Puri May 28 '15 at 21:41
  • also not in controller this should go in a helper class which is app/helpers folder – Manish Puri May 28 '15 at 21:42
0

You should look into https://stackoverflow.com/a/7860493/1657377, a presenter or decorator pattern might fit in here. But this logic definitely does not belong into the controller.

Community
  • 1
  • 1
jethroo
  • 2,086
  • 2
  • 18
  • 30