Ruby on rails 您将如何重构此HAML代码
我有一个haml代码片段,表示一个喜欢/不喜欢按钮Ruby on rails 您将如何重构此HAML代码,ruby-on-rails,refactoring,haml,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')
- 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')
但我觉得这很糟糕,特别是对于这个令人敬畏的图标。。。有什么想法吗
- 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')
我相信有更好的方法,但有了您提供的代码,我会这么做。我认为您可以进一步重构,但这需要使用控制器&合并类以减少特定性(即使用container
div
s)提出改进和批评功能代码的问题更适合于。您的意思是喜欢“.liked”和“.notliked”按钮周围的类?是的,这样-它将使您能够使用CSS设置所有元素的样式,而不是使用Rails单独进行。这难道不是将#{class}移到按钮之外吗?我仍然需要一个条件来窥视正确的类。我仍然需要计算按钮的方法。看不出css类在这里有什么帮助:(css只会影响样式-这是我能看到的部分问题。如果需要更改Rails特定的内容,您只需使用条件语句(如果
)就重构而言,它基本上只是一个干涸你的风格和结构的例子——这是两个不同的元素。你不能有一个名为class
的变量,它是一个关键字,这段代码会给出一个错误,你需要使用其他东西(icon\u color
)。