使用控制器管理渲染逻辑而不是视图

Using the controller to manage render logic rather than view

我要求的不是代码作为答案,而是一种资源或一些一般指导。

我有一个用户索引页。对于每个用户,我检查每个用户相对于当前用户的 "friend status"。可以想象,在视图页面中这是一个相当冗长的 if 和 elsif 语句。基本上是:

<% 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" %>

我把这整个逻辑都放在了view page里面,很繁琐。我想稍微清理一下并将其存放在控制器中(如果需要的话)。

任何指导将不胜感激。我想象有一种方法可以 return 图标的类型或呈现某种 html 代码并将其传递到视图中。谢谢!!

帮助方法就是答案..

在你的助手中用某种方法移动它,比如

def my_awesome_helper_method
- logic -
end

并在视图中调用

<%=my_awesome_helper_method %>

干净多了...!

您应该查看 ,演示者或装饰器模式可能适合这里。但是这个逻辑肯定不属于controller。