Vlad Cenan Vlad Cenan - 3 months ago 12
Ruby Question

Remove extra characters from thread script

I've got a ruby script which check microservices version from each microservice API. I try to run this with bamboo and return the result as a html table.

...
h = {}
threads = []
service = data_hash.keys
service.each do |microservice|
threads << Thread.new do
thread_id = Thread.current.object_id.to_s(36)
begin
h[thread_id] = ""
port = data_hash["#{microservice}"]['port']

nodes = "knife search 'chef_environment:#{env} AND recipe:#

{microservice}' -i 2>&1 | tail -n 2"
node = %x[ #{nodes} ].split
node.each do |n|
h[thread_id] << "\n<html><body><h4> Node: #{n} </h4></body></html>\n"
uri = URI("http://#{n}:#{port}/service-version")
res = Net::HTTP.get_response(uri)
status = Net::HTTP.get(uri)
data_hash = JSON.parse(status)
name = data_hash['name']
version = data_hash['version']
h[thread_id] << "<table><tr><th> #{name}:#{version} </th></tr></table>"
end

rescue => e
h[thread_id] << "ReadTimeout Error"
next
end
end
end

threads.each do |thread|
thread.join
end

ThreadsWait.all_waits(*threads)
puts h.to_a


The issue is that I want to output name and version into a html table and if I put threads it generates some random characters between each line:

<table><tr><th> microservice1:2.10.3 </th></tr></table>
bjfsw
<table><tr><th> microservice2:2.10.8 </th></tr></table>

Answer

The random characters are the keys of the hash generated with to_s(36).

Replace the puts h.to_a with something like

puts h.values.join("\n")

And you will only see the data and not the keys.

You can use kernel#p h or puts h.inspect to see this.