我如何重构这个更干?

时间:2016-11-11 20:08:41

标签: ruby-on-rails ruby refactoring ruby-on-rails-5

基本上我在这里做的是跟踪4种不同类型的ratings。如果存在任何评级,我想对该评级应用不同的css类,然后将默认的css类应用于该行中呈现的其他跨度。

ratings = ["speed", "tackling", "passing", "dribbling"]
ratings.each do |rating|
  content_tag :div, class: "col-lg-3" do
    if rating_param.eql? rating
      if rating.eql? "speed"
        content_tag :span, class: "label label-success label-lg" do
          "#{rating.capitalize}: #{profile.ratings.find_by(user: current_user)[rating]}"
        end
      elsif rating.eql? "tackling"
        content_tag :span, class: "label label-tackling label-lg" do
          "#{rating.capitalize}: #{profile.ratings.find_by(user: current_user)[rating]}"
        end
      end
    else
      content_tag :span, class: "label label-default" do
        "#{rating.capitalize}: #{profile.ratings.find_by(user: current_user)[rating]}"
      end
    end
  end
end

基本上我需要做的是将rating映射到班级。

例如,它可能如下所示:

speed: success, tackling: info, dribbling: primary, passing: warning

因此,如果评分为speed,则应该应用课程success,依此类推。

我如何重构这个,所以这不是一堆丑陋的if语句?

2 个答案:

答案 0 :(得分:2)

(不是一个完整的答案,但在评论中没用。)

(非常)大致:

rating_classes = {
  'speed'     => 'label-success label-lg',
  'tackling'  => 'label-tackling label-lg',
  'passing'   => 'whatever',
  'dribbling' => 'whatever'
}

rating_class = rating_classes[rating_param] || 'label-default'

content_tag :div, class: "col-lg-3" do
  content_tag :span, class: "label #{rating_class}" do
    "#{rating.capitalize}: #{profile.ratings.find_by(user: current_user)[rating]}"
  end
end

答案 1 :(得分:0)

你也可以尝试这个..

rating_classes = {
  "speed"     => "label label-success label-lg",
  "tackling"  => "label label-tackling label-lg",
  "passing"   => "label label-default",
  "dribbling" => "label label-default"
}

profile_rating = profile.ratings.find_by(user: current_user)

content_tag :div, class: "col-lg-3" do
  rating_classes.each do |rating, klass|
    content_tag :span, class: "#{klass}" do
      "#{rating.capitalize}: #{profile_rating[rating]}"
    end
  end
end

您已在循环中编写profile.ratings.find_by(user: current_user),执行相同的查询4次,这可能会降低性能。