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 to share