重构 - 第 11 章,练习 3 Rails 教程第 2 版



还有其他人正在为 Michael Hartl 的 Rails 教程第 2 版学习第 11 章练习吗?

第 11 章练习 3 提出以下问题:重构清单 11.31,为以下/关注者页面、主页和用户显示页面通用的代码添加部分。

我在主页、用户显示页面或show_follow页面中没有看到任何值得重构的内容

如果有人想出一些值得做这个练习的东西,很想知道。

谢谢!

你可以重构清单 11.31 中的第一个代码块:

<section>
  <%= gravatar_for @user %>
  <h1><%= @user.name %></h1>
  <span><%= link_to "view my profile", @user %></span>
  <span><b>Microposts:</b> <%= @user.microposts.count %></span>
</section>

因为它本质上与主页上使用的视图\shared_user_info.html.erb 部分相同(清单 10.32)。 因此,您可以将上面的代码块替换为以下内容:

<%= render 'shared/user_info' %> 

请注意,您还需要将<% @user ||= current_user %>添加到 view\shared_user_info.html.erb partial 的顶部(这与清单 11.20 中添加到统计信息部分所需的内容相同)。

此外,feed_item + 提要部分与用户 + 微帖子部件之间存在一些重复(尽管不是完全重复),其中根据显示的页面(follow_show、主页或个人资料),列出了一个或多个元素(名称、头像、管理员删除链接、微帖子内容、微帖子时间戳和微帖子删除链接)。 这些可能也可以重构以消除feed_item+提要部分,并根据页面将它们替换为用户+微帖子部分的组合。

我刚刚完成了这个练习,并找到了一个有效的解决方案。

首先,我更改了app/views/shared/_user_info.html.erb,以使用@user变量(如果已设置),否则使用current_user变量。

app/views/shared/_user_info.html.erb:

<% if @user %>
    <%= link_to gravatar_for(@user, size: 52), @user %>
    <h1>
        <%= @user.name %>
    </h1>
    <span>
        <%= link_to "view my profile", @user %>
    </span>
    <span>
        <%= pluralize(@user.microposts.count, "micropost") %>
    </span>
<% else %>
    <%= link_to gravatar_for(current_user, size: 52), current_user %>
    <h1>
        <%= current_user.name %>
    </h1>
    <span>
        <%= link_to "view my profile", current_user %>
    </span>
    <span>
        <%= pluralize(current_user.microposts.count, "micropost") %>
    </span>
<% end %>

然后我用部分 _user_info.html.erb 替换了 app/views/users/show_follow.hmtl.erb 中的相应信息。

app/views/users/show_follow.hmtl.erb:

<div class="row">
    <aside class="span4">
        <section>
            <%= render 'shared/user_info' %>
        </section>
        <section>
            <%= render 'shared/stats' %>
            <% if @users.any? %>
                <div class="user_avatars">
                    <% @users.each do |user| %>
                        <%= link_to gravatar_for(user, size: 30), user %>
                    <% end %>
                </div>
            <% end %>
        </section>
    </aside>
    <div class="span8">
        <h3><%= @title %></h3>
        <% if @users.any? %>
            <ul class="users">
                <%= render @users %>
            </ul>
            <%= will_paginate %>
        <% end %>
    </div>
</div>

我希望这个答案对任何学习 M. Hartl 教程的人有所帮助。

最新更新