【问题标题】:How to refactor this piece of code [closed]如何重构这段代码[关闭]
【发布时间】:2013-08-13 13:20:29
【问题描述】:

我是 ruby​​ on rails 的新手,在这个项目中我使用的是 ruby​​ 2.0 和 rails 3.0

我想知道这段代码是否可以重构,因为它是

unless params["ot_code"].nil?       
    ots = params["ot_code"].gsub(/\r\n?/, "").gsub(";","','").upcase
    ots[ots.length,1] = "'"
    ots =  ots.rjust(ots.length+1,"'")
end

unless params["circuit_id_multiple"].nil?
    multiple_circuit = params["circuit_id_multiple"].gsub(/\r\n?/, "").gsub(";","','")
    multiple_circuit[multiple_circuit.length,1] = "'"
    multiple_circuit = multiple_circuit.rjust(multiple_circuit.length+1,"'")
end

unless params["multiple_element_code"].nil?
    multiple_element_code = params["multiple_element_code"].gsub(/\r\n?/, "").gsub(";","','")
    multiple_element_code[multiple_element_code.length,1] = "'"
    multiple_element_code = multiple_element_code.rjust(multiple_element_code.length+1,"'")
end

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3 refactoring ruby-2.0


【解决方案1】:
  1. 不要使用双重否定

    Rails 参数是字符串或nil。所以而不是:

    unless params["ot_code"].nil?
    

    只写:

    if params["ot_code"]
    
  2. 保持简单

    我想这应该用单引号包裹一个字符串:

    ots[ots.length,1] = "'"
    ots = ots.rjust(ots.length+1,"'")
    

    您可以改为简单地写:

    ots = "'#{ots}'"
    
  3. 不要重复自己

    您正在重复相同的处理步骤 3 次。改写一个方法:

    def convert(str)
      str = str.gsub(/\r\n?/, "")  # remove newlines
      str = str.gsub(";", "','")   # convert semicolons
      "'#{str}'"                   # wrap in single quotes
    end
    
    def action_method
      ots = convert(params["ot_code"]).upcase if params["ot_code"]
      multiple_circuit = convert(params["circuit_id_multiple"]) if params["circuit_id_multiple"]
      multiple_element_code = convert(params["multiple_element_code"]) if params["multiple_element_code"]
    end
    

希望这会有所帮助。

【讨论】:

  • unless params["ot_code"].nil?if params["ot_code"] 不同。 nil 的第一个测试和第二个测试可能会失败,如果它是 false 而不是 nil
  • 没错,但在这个上下文(Rails)中,它是一个字符串或nil
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多