你会如何重构这个HAML代码?

时间:2014-06-01 09:10:55

标签: ruby-on-rails refactoring haml

我有这个haml片段代表喜欢/不喜欢的按钮

- if @post.liked_by?(current_user)
  = button_to post_likes_path(@post), method: :delete, class: 'post-like-btn' do
    %i.fa.fa-heart.color-red
    = @post.likes
    .footer-caption= pluralize(@post.likes, 'like', 'likes')
- else
  = button_to post_likes_path(@post), method: :post, class: 'post-like-btn' do
    %i.fa.fa-heart
    = @post.likes
    .footer-caption= pluralize(@post.likes, 'like', 'likes')

但我真的觉得它可能会干涸。我的第一次尝试:

= button_to post_likes_path(@post), method: (@post.liked_by?(current_user) ? :delete : :post), class: 'post-like-btn' do
  %i{class: "fa fa-heart#{@post.liked_by?(current_user) ? ' color-red' : ''}"}
  = @post.likes
  .footer-caption= pluralize(@post.likes, 'like', 'likes')

但是我发现这很糟糕,尤其是FontAwesome图标......任何想法?

1 个答案:

答案 0 :(得分:2)

- method = @post.liked_by?(current_user) ? :delete : :post
- class  = @post.liked_by?(current_user) ? ".color-red" : ""

= button_to post_likes_path(@post), method: #{method}, class: 'post-like-btn' do
    %i.fa.fa-heart#{class}
       = @post.likes
       .footer-caption= pluralize(@post.likes, 'like')

我确信这是一种更好的方式,但是根据您提供的代码,这就是我所做的。我认为你可以进一步重构,但它需要使用控制器和放大器。将类合并为不太具体(I.E使用容器div s)