且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

010 重构用户名(第一部分)

更新时间:2022-10-04 18:55:48

Learn how to clean up your code through refactoring. This episode will show you how to move code from the view into the model to remove duplication and simplify the view.
 
 
学习如何通过重构来整理你的代码。这节将学习如何将视图中的代码放到模型里,从而简化代码,并消除视图中的重复代码。
 
一开始的代码:
 
#index.html
 
<h2>Users</h2>
<ul>
<%= for user in @users%>
  <li>
    <a href="<%= user_path(user)%>">
    <%= user.first_name%>
    <%= "#{user.middle_initial}." unless user.middle_initial.nil?%> 
    <%= user.last_name%> 
   </a>
  </li>
<% end %>
</ul>
 
 
#show.rhtml
 
<h1>Profile</h1>
<p>
Name:
    <%= user.first_name%>
    <%= "#{user.middle_initial}." unless user.middle_initial.nil?%> 
    <%= user.last_name%> 
</p>
<%= link_to "Users List", users_path%>
 
 
很明显,在两个视图中,对于名字的显示这部分代码首先是有了重复了。
 
对于名字的显示,分为三部分,first_name, middle_initial, last_name
对于middle_initial来说,如果存在才显示。
 
那么对于这种代码,要重构,首先想到的是使用helper。但是其中没有html代码,经过考虑,还是把他们放到model里最合适。所以:
在视图中对于名字的属性可以这么调用:
 
<h1>Profile</h1>
<p>
Name:
    <%= user.full_name%></p>
<%= link_to "Users List", users_path%>
 
在model里写一个full_name的方法:
 
# models/user.rb
def full_name
  name = first_name + " "
  name += "#{middle_initial}" unless middle_initial.nil?
  name += last_name
  name
end




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/131601,如需转载请自行联系原作者