如何重构这段代码

时间:2013-08-13 13:20:30

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

我是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

1 个答案:

答案 0 :(得分:3)

  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
    
  4. 希望这有帮助。