原创作者: hideto   阅读:1263次   评论:0条   更新时间:2011-05-26    
看这个显示用户Profile的页面:
<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 %>

当别的页面需要显示用户名时,我们又得将上述代码copy一遍,敏感的开发人员可能已经闻到“风水”或bad smell了吧。

好,我们来重构:
class User < ActiveRecord::Base
  def full_name
    name = first_name
    name += "#{middle_initial}." unless middle_initial.nil?
    name += last_name
    name
  end
end

页面就可以这样写了:
<h1>Profile</h1>
<p>
  Name:
  <%= @user.full_name %>
</p>

<% link_to 'Users List', users_path %>
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics