Skip to content

Instantly share code, notes, and snippets.

@atheiman
Created February 16, 2017 03:21
Show Gist options
  • Save atheiman/17563d78665001d927e2d6a2ee6e5fe8 to your computer and use it in GitHub Desktop.
Save atheiman/17563d78665001d927e2d6a2ee6e5fe8 to your computer and use it in GitHub Desktop.
output = 'peer count: 6
ip address: 1.2.3.4
status: up
client version: 1.2.3
ip address: 1.2.3.5
status: up
client version: 1.3.0
ip address: 1.2.3.10
status: down
client version: 1.2.2
ip address: 1.2.3.55
status: up
client version: 1.2.3
'
peer_strings = output.split("\n\n")
# pop / shift off the first element (peer count)
# https://ruby-doc.org/core-2.3.3/Array.html#method-i-shift
peer_strings.shift
def peer_hash_from_string(str)
# find values in string output and assign them to variables using named captures
# https://ruby-doc.org/core-2.3.3/Regexp.html#class-Regexp-label-Capturing
/^ip address:\s+(?<ip_address>[\d\.]+)$/ =~ str
/^status:\s+(?<status>[\w]+)$/ =~ str
/^client version:\s+(?<client_version>[\d\.]+)$/ =~ str
# return the hash
{
ip_address: ip_address,
status: status,
client_version: client_version
}
end
peers = []
peer_strings.each do |str|
peers << peer_hash_from_string(str)
end
require 'pp'
pp peers
require 'rspec'
describe 'gluster peer status output parsing' do
it do
expect(peer_strings.length).to eq(4)
end
it do
expect(peers.length).to eq(4)
expect(peers[1]).to eq(
ip_address: '1.2.3.5',
status: 'up',
client_version: '1.3.0'
)
end
end
tmp $ rspec gluster_peer_status.rb
[{:ip_address=>"1.2.3.4", :status=>"up", :client_version=>"1.2.3"},
{:ip_address=>"1.2.3.5", :status=>"up", :client_version=>"1.3.0"},
{:ip_address=>"1.2.3.10", :status=>"down", :client_version=>"1.2.2"},
{:ip_address=>"1.2.3.55", :status=>"up", :client_version=>"1.2.3"}]
..
Finished in 0.00201 seconds (files took 0.31168 seconds to load)
2 examples, 0 failures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment