Skip to content

Commit fa36434

Browse files
committed
✨ Add #logout! to combine logout and disconnect
A logout command that also disconnects, even if logout raises an exception, and doesn't raise exceptions when already disconnected would be very useful in situations where the connection MUST be gracefully closed, e.g. for security or tests. Although the change is relatively insignificant, changing #logout to also ignore exceptions and immediately call #disconnect would be backwards incompatible. So a new method was created.
1 parent 4b54a07 commit fa36434

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

lib/net/imap.rb

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -868,7 +868,7 @@ def client_thread # :nodoc:
868868

869869
# Disconnects from the server.
870870
#
871-
# Related: #logout
871+
# Related: #logout, #logout!
872872
def disconnect
873873
return if disconnected?
874874
begin
@@ -1067,11 +1067,34 @@ def noop
10671067
# to inform the command to inform the server that the client is done with
10681068
# the connection.
10691069
#
1070-
# Related: #disconnect
1070+
# Related: #disconnect, #logout!
10711071
def logout
10721072
send_command("LOGOUT")
10731073
end
10741074

1075+
# Calls #logout then, after receiving the TaggedResponse for the +LOGOUT+,
1076+
# calls #disconnect. Returns the TaggedResponse from +LOGOUT+. Returns
1077+
# +nil+ when the client is already disconnected, in contrast to #logout
1078+
# which raises an exception.
1079+
#
1080+
# If #logout raises a StandardError, a warning will be printed but the
1081+
# exception will not be re-raised.
1082+
#
1083+
# This is useful in situations where the connection must be dropped, for
1084+
# example for security or after tests. If logout errors need to be handled,
1085+
# use #logout and #disconnect instead.
1086+
#
1087+
# Related: #logout, #disconnect
1088+
def logout!
1089+
logout unless disconnected?
1090+
rescue => ex
1091+
warn "%s during <Net::IMAP %s:%s>logout!: %s" % [
1092+
ex.class, host, port, ex
1093+
]
1094+
ensure
1095+
disconnect
1096+
end
1097+
10751098
# Sends a {STARTTLS command [IMAP4rev1 §6.2.1]}[https://www.rfc-editor.org/rfc/rfc3501#section-6.2.1]
10761099
# to start a TLS session.
10771100
#

test/net/imap/fake_server/test_helper.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ def with_client(*args, **kwargs)
2323
yield client
2424
ensure
2525
if client && !client.disconnected?
26-
client.logout rescue pp $!
27-
client.disconnect unless client.disconnected?
26+
client.logout!
2827
end
2928
end
3029

0 commit comments

Comments
 (0)