How can I refactor this piece of Ruby code to remove duplication?

I don't have a problem per se, but I am completely new to Ruby. I have the following 3 repeatable bits of code in one method and I would like to know how a true rubyist should remove duplication first and secondly make it more reusable.

Here is the code in question:

file = File.new( destination)
doc = REXML::Document.new file

doc.elements.each("configuration/continuity2/plans") do |element| 
  element.attributes["storebasedir"]  =  "#{TEST_OUTPUT_DIRECTORY}"
end

doc.elements.each("configuration/add").each do |database|
  database.raw_attributes = database.attributes.merge("connectionstring" => "#{TEST_CONNECTION_STRING}")
end

doc.elements.each("configuration/connectionStrings/plans") do |connectionString|
  connectionString.raw_attributes = connectionString.attributes.merge("connectionString" => "#{TEST_CONNECTION_STRING}")
end   

      

Any advice is appreciated.

+1


source to share


3 answers


The last two blocks can be replaced with

["add", "connectionStrings/plans"].each do |elt_name|
  doc.elements.each("configuration/#{elt_name}").do |elt|
    elt.raw_attributes = elt.attributes.merge("connectionString" => "#{TEST_CONNECTION_STRING}")
  end
end

      



I guess the random difference between "connectionstring" and "connectionString" was accidental. If so, it clearly illustrates the benefit of de-duplication.

Alternatively, you can replace "#{TEST_CONNECTION_STRING}"

with TEST_CONNECTION_STRING

.

+3


source


You can try to add a method that tries to be as generic as possible to avoid this, but they are vastly different for me ... You run the risk of having complex code to be able to wrap these strings in one method.



+2


source


I see no duplication. The collections you iterate over are significantly different and the operations you perform on each element are also very different. I agree with Olivier that any attempt to remove duplication will simply lead to more complex code.

+2


source







All Articles