在RubyonRails中重构重if语句的有效方法是什么



重构重if语句的有效方法是什么

鼓励所有建议

<% if @user.plan_id == 1 %>
      <span class="label label-info">Plan1</span>
  <% elsif @user.plan_id == 2 %>
      <span class="label label-warning">Plan2</span>
  <% elsif @user.plan_id == 3 %>
      <span class="label label-info">Plan3</span>
  <% elsif @user.plan_id == 4 %>
      <span class="label label-warning">Plan4</span>
  <% elsif @user.plan_id == 5 %>
      <span class="label label-info">Plan5</span>
  <% elsif @user.plan_id == 6 %>
      <span class="label label-warning">Plan6</span>
  <% elsif @user.plan_id == 7 %>
      <span class="label label-info">Plan7</span>   
  <% elsif @user.plan_id == 8 %>
      <span class="label label-warning">Plan8</span>
<% end %>

这是一个助手模块的作业,类似于以下内容:

module UserPlanHelper
  PLANS = {
    1 => [ "info", "Plan1" ],
    2 => [ "warning", "Plan2" ],
    3 => [ "info", "Plan3" ],
    4 => [ "warning", "Plan4" ],
    5 => [ "info", "Plan5" ],
    6 => [ "warning", "Plan6" ],
    7 => [ "info", "Plan7" ],
    8 => [ "warning", "Plan8" ]
  }
  def plan_details(plan_id)
    yield(PLANS[plan_id])
  end
end

如果在你的控制器中使用,这会将你的代码简化为:

<%= plan_details(@user.plan_id) do |label_class, label| %>
  <span class="label label-<%= label_class %>"><%= label %></span>
<%- end %>

plan_id是否引用Plan模型?如果没有,我建议创建一个具有label属性和elite标志的。那么,你的声明是:

<span class="label label-<%= @user.plan.elite ? 'warning' : 'info' %>}">
  <%= @user.plan.label %>
</span>

您可以使用case

<% case @user.plan_id %>
<% when 1 %>
    <span class="label label-info">CONTRIBUTOR</span>
<% when 2 %>
    <span class="label label-warning">ELITE CONTRIBUTOR</span>
<% when 3 %>
     <span class="label label-info">TECHNICIAN</span>
<% when 4 %>
     <span class="label label-warning">ELITE TECHNICIAN</span>
<% when 5 %>
     <span class="label label-info">CENTER</span>
<% when 6 %>
     <span class="label label-warning">ELITE CENTER</span>
<% when 7 %>
     <span class="label label-info">AFFAIR</span>   
<% when 8 %>
      <span class="label label-warning">ELITE AFFAIR</span>
<% end %>

定义一个辅助方法:

def plan_hash
  {
    1 => { :klass => "label-info",    :description => "Plan1" },
    2 => { :klass => "label-warning", :description => "Plan2" },
    3 => { :klass => "label-info",    :description => "Plan3" },
    4 => { :klass => "label-warning", :description => "Plan4" },
    5 => { :klass => "label-info",    :description => "Plan5" },
    6 => { :klass => "label-warning", :description => "Plan6" },
    7 => { :klass => "label-info",    :description => "Plan7" },
    8 => { :klass => "label-warning", :description => "Plan8" }
  }
end

然后,在你看来:

<span class="label <%= plan_hash[@user.plan_id][:klass] %>"><%= plan_hash[@user.plan_id][:description] %></span>
<span class="label label-<%= @user.add_warning? ? 'warning' : 'info' %>">
  Plan<%= @user.plan_id.to_s %>
</span>

在您的用户模型中使用此方法:

def add_warning?
  self.plan_id.in?([2, 4, 6, 8])
end

相关内容

  • 没有找到相关文章

最新更新