Rails 请问下面这行代码如何重构的漂亮点。

huobazi · 2013年07月06日 · 最后由 miclle 回复于 2013年07月06日 · 4131 次阅读

current_user.following?(user) 的判断有点多

<%= link_to current_user.following?(user)? unfollow_user_path(user) : follow_user_path(user), 
         :class => current_user.following?(user)? 'btn btn-danger btn-block unfollow' : 'btn btn-primary btn-block follow',
         :method => :put,
         :remote => true do %>
         <strong>
           <%= current_user.following?(user)? '取消关注' : '关注' %>
         </strong>
         <span></span>
       <% end %>

请大家帮忙看看能如何重构的漂亮点,谢谢。

可是,明显来说,判断是必要的啊。实在看不惯,就把判断结果放到个变量中,或者把「关注」和「取消关注」放在同路径接口中,让 controller 作判断,不过这样子对用户不友好!

我之前的做法是这样: help:

# Painter follow button
 def painter_follow_button(painter)
     if current_user.favorite? painter
       render "painters/followed", :painter => painter
     else
       render "painters/follow", :painter => painter
     end
 end

_followed.html.erb

<%= link_to "已关注", unfollow_painter_path(painter), :remote => true, :method => :post, :class => "action", :id => "follow-action", "data-disable-with" => "请稍候...", "data-over-text" => "取消关注" %>

_follow.html.erb

<%= link_to "关注TA", follow_painter_path(painter), :remote => true, :method => :post, :class => "action", :id => "follow-action", "data-disable-with" => "请稍候..." %>

follow.js.erb

$('#follow-action').replaceWith("<%= escape_javascript(render('followed', :painter => @painter)) %>");

unfollow.js.erb

$('#follow-action').replaceWith("<%= escape_javascript(render('follow', :painter => @painter)) %>");

嗯,支持藏到 helper 里

helper + #{}

#5 楼 @huobazi

link_to 里有一个"data-over-text的属性,我是 JS 来切换显示文字的

// over text
// <a href="/painters/1/unfollow" data-over-text="取消关注" data-remote="true">已关注</a>
// <a href="/u/2/unfollow" data-over-text="取消关注" over-rel="#follow-2-text">
//   <span id="follow-2-text">已关注</span>
// </a>

$(document).delegate('[data-over-text]', 'mouseover', function() {
  var $element = $(this);
  var $target = $($element.attr('over-rel'));
  $element.data('original', $element.text());
  $target = $target.size() > 0 ? $target : $element;
  $target.text($element.attr('data-over-text'));
});

$(document).delegate('[data-over-text]', 'mouseout', function() {
  var $element = $(this);
  var $target = $($element.attr('over-rel'));
  $target = $target.size() > 0 ? $target : $element;
  $target.text($element.data('original'));
});
需要 登录 后方可回复, 如果你还没有账号请 注册新账号