Reputation: 1766
I want to use this Ruby code to generate XML file with 10 terminals:
module WriteXML
def write_data_xml
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.genesis {
xml.terminals {
/// create here some loop to iterate
xml.terminal {
xml.name "PPRO_Terminal"
xml.type "ppro"
xml.credentials {
xml.username 'user1'
xml.password 'passwd1'
xml.token '5e36e51de2dde626804a8772dc26238c4d722bbc'
}
}}
////////
}
end
puts builder.to_xml
file = File.new("credentials.xml", "w")
File.open('credentials.xml', 'w') do |file|
file << builder.to_xml
end
end
end
How I can use iteration in order to save code when I want to create many terminals?
Upvotes: 1
Views: 80
Reputation: 42207
Depends on where you keep the data that identify these terminals, is that in a table ? Then you could do something like this
def write_data_xml credential
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.genesis {
xml.terminals {
xml.terminal {
xml.name credential.name
xml.type credential.type
xml.credentials {
xml.username credential.username
xml.password credential.password
xml.token credential.token
}
}}
}
end
File.open("credentials.xml", "a+") { |file| file.write builder.to_xml}
end
end
Suppose you use activerecord you could then
Credentials.each do |credential|
write_data_xml credential
end
If no table, you could use an array of structs where you gather the needed data.
EDIT on request of the OP, here a version that doesn't follow the single responsibility principle
def write_data_xml
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.genesis {
xml.terminals {
Credentials.each do |credential|
xml.terminal {
xml.name credential.name
xml.type credential.type
xml.credentials {
xml.username credential.username
xml.password credential.password
xml.token credential.token
}
end
}}
}
end
File.write("credentials.xml", builder.to_xml)
end
end
EDIT2
here an example of how to use this with an array of structs since there is no database yet
Credentials = []
Credential = Struct.new(:name, :type, :username, :password, :token)
Credentials << Credential.new('PPRO_Terminal', 'ppro', 'user1', 'passwd1', '5e36e51de2dde626804a8772dc26238c4d722bbc')
Credentials << Credential.new( 'PPRO_Terminal2', 'ppro', 'user2', 'passwd2', '...')
p Credentials
[#<struct Credential name="PPRO_Terminal", type="ppro", username="user1", password="passwd1", token="5e36e51de2dde626804a8772dc26238c4d722bbc">, #<struct Credential name="PPRO_Terminal2", type="ppro", username="user2", password="passwd2", token="...">]
NB at least, create this outside of the method
Upvotes: 1