Skip to content

Instantly share code, notes, and snippets.

@spheromak
Last active August 29, 2015 13:56
Show Gist options
  • Save spheromak/9147685 to your computer and use it in GitHub Desktop.
Save spheromak/9147685 to your computer and use it in GitHub Desktop.
Hosname parts parser
$ rspec -c -fd foo_spec.rb
Hostname
converts hostnmber to single int
handles tenths numbered hosts
handles initial number names
handles 100ths numbered hosts
handles no domain
handled arbitrary dots
handled dashes
handles multiple numbers in name
handled numbered subdomain
Finished in 0.00146 seconds
9 examples, 0 failures
#!/bin/env ruby
# simple test of hostname parser
class Hostname
attr_reader :name, :number, :full_name
def initialize(hostname)
parse = hostname.match(/([A-Za-z0-9\-\_]+[A-Za-z\-\_]+)(\d+\b)/).to_a || []
@full_name = parse.fetch(0, hostname)
@name = parse.fetch(1, hostname)
@number = parse.fetch(2, hostname).to_i
end
end
require 'rspec'
describe 'Hostname' do
it 'converts hostnmber to single int' do
h = Hostname.new('foo03.foo')
h.number.should eql 3
h.name.should eql 'foo'
h.full_name.should eql 'foo03'
end
it 'handles tenths numbered hosts' do
h = Hostname.new('foo30.foo')
h.number.should eql 30
h.name.should eql 'foo'
h.full_name.should eql 'foo30'
end
it 'handles initial number names' do
h = Hostname.new('33foo30.foo')
h.number.should eql 30
h.name.should eql '33foo'
h.full_name.should eql '33foo30'
end
it 'handles 100ths numbered hosts' do
h = Hostname.new('foo300.foo')
h.number.should eql 300
h.name.should eql 'foo'
h.full_name.should eql 'foo300'
end
it 'handles no domain' do
h = Hostname.new('foo03')
h.number.should eql 3
h.name.should eql 'foo'
h.full_name.should eql 'foo03'
h = Hostname.new('03')
h.number.should eql 3
h.name.should eql '03'
h.full_name.should eql '03'
end
it 'handled arbitrary dots' do
h = Hostname.new('foo03.a.b.c.d')
h.number.should eql 3
h.name.should eql 'foo'
h.full_name.should eql 'foo03'
end
it 'handled dashes' do
h = Hostname.new('foo-bar03.a.b.c.d')
h.number.should eql 3
h.name.should eql 'foo-bar'
h.full_name.should eql 'foo-bar03'
h = Hostname.new('foo-03.a.b.c.d')
h.number.should eql 3
h.name.should eql 'foo-'
h.full_name.should eql 'foo-03'
end
it 'handles multiple numbers in name' do
h = Hostname.new('f40foo03')
h.number.should eql 3
h.name.should eql 'f40foo'
h.full_name.should eql 'f40foo03'
end
it 'handled numbered subdomain' do
h = Hostname.new('foo03.a10.b30.c.d')
h.number.should eql 3
h.name.should eql 'foo'
h.full_name.should eql 'foo03'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment