Skip to content

Commit

Permalink
updated gethostname to avoid deprecation warning
Browse files Browse the repository at this point in the history
warning: Socket.gethostbyname is deprecated; use Addrinfo.getaddrinfo instead.
  • Loading branch information
skaes committed Aug 14, 2022
1 parent da0afde commit 7034bf0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
8 changes: 2 additions & 6 deletions lib/beetle.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,8 @@ class NoMessageSent < Error; end
# determine the fully qualified domainname of the host we're running on
def self.hostname
name = Socket.gethostname
parts = name.split('.')
if parts.size > 1
name
else
Socket.gethostbyname(parts.first).first rescue name
end
host = name.split('.').first
Addrinfo.getaddrinfo(host, nil, nil, :STREAM, nil, Socket::AI_CANONNAME).first.canonname rescue name
end

# use ruby's autoload mechanism for loading beetle classes
Expand Down
11 changes: 7 additions & 4 deletions test/beetle/beetle_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@

module Beetle
class HostnameTest < Minitest::Test
test "should use Socket.gethostname if returned name name is fully qualified" do
test "should use canonical name if possible " do
addr = mock("addr")
addr.expects(:canonname).returns("a.b.com")
Socket.expects(:gethostname).returns("a.b.com")
Addrinfo.expects(:getaddrinfo).with("a", nil, nil, :STREAM, nil, Socket::AI_CANONNAME).returns([addr])
assert_equal "a.b.com", Beetle.hostname
end

test "should use Socket.gethosbyname if returned name name is not fully qualified" do
test "should use Socket.gethostbyname if Addrinfo raises" do
Socket.expects(:gethostname).returns("a")
Socket.expects(:gethostbyname).with("a").returns(["a.b.com"])
assert_equal "a.b.com", Beetle.hostname
Addrinfo.expects(:getaddrinfo).with("a", nil, nil, :STREAM, nil, Socket::AI_CANONNAME).raises("murks")
assert_equal "a", Beetle.hostname
end
end
end

0 comments on commit 7034bf0

Please sign in to comment.