HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Is there a way to refactor this code?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thiswaycodethererefactor

Problem

I'm new to ruby on rails, on this project I'm using Ruby 2.0 and Ruby on Rails 3.0.

I would like to know if this piece of code can be refactored, as it is

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

Solution

I'm a little worried about your gsubs, but assuming this is what you want to do:

def replace_and_wrap(str)
  return nil if str.nil?
  %Q{'#{str.gsub(/\r\n?/, "").gsub(";","','")}'}  
end

ots = replace_and_wrap(params["ot_code"])
multiple_circuit = replace_and_wrap(params["circuit_id_multiple"])
multiple_element_code = replace_and_wrap(params["multiple_element_code"])


Note that this changes the behavior of your code slightly: variables (like ots) are set to nil if the param is nil, rather than remaining undefined. Depending on how you are using these variables, this behavior is probably better anyway.

Code Snippets

def replace_and_wrap(str)
  return nil if str.nil?
  %Q{'#{str.gsub(/\r\n?/, "").gsub(";","','")}'}  
end

ots = replace_and_wrap(params["ot_code"])
multiple_circuit = replace_and_wrap(params["circuit_id_multiple"])
multiple_element_code = replace_and_wrap(params["multiple_element_code"])

Context

StackExchange Code Review Q#29687, answer score: 2

Revisions (0)

No revisions yet.