Skip to content

Commit 6c81f53

Browse files
committed
Merge pull request #319 from mattbrictson/backend-thread-local
Add SSHKit::Backend.current
2 parents 67eb3a0 + 8032db6 commit 6c81f53

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

Diff for: CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ appear at the top.
1717
[PR #308](https://github.com/capistrano/sshkit/pull/308) @mattbrictson
1818
* `SSHKit::Backend::Printer#test` now always returns true
1919
[PR #312](https://github.com/capistrano/sshkit/pull/312) @mikz
20+
* Add `SSHKit::Backend.current` so that Capistrano plugin authors can refactor
21+
helper methods and still have easy access to the currently-executing Backend
22+
without having to use global variables.
23+
[PR #319](https://github.com/capistrano/sshkit/pull/319) @mattbrictson
2024

2125
## 1.8.1
2226

Diff for: lib/sshkit/backends/abstract.rb

+16
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,19 @@ module Backend
44

55
MethodUnavailableError = Class.new(SSHKit::StandardError)
66

7+
# The Backend instance that is running in the current thread. If no Backend
8+
# is running, returns `nil` instead.
9+
#
10+
# Example:
11+
#
12+
# on(:local) do
13+
# self == SSHKit::Backend.current # => true
14+
# end
15+
#
16+
def self.current
17+
Thread.current["sshkit_backend"]
18+
end
19+
720
class Abstract
821

922
extend Forwardable
@@ -12,7 +25,10 @@ class Abstract
1225
attr_reader :host
1326

1427
def run
28+
Thread.current["sshkit_backend"] = self
1529
instance_exec(@host, &@block)
30+
ensure
31+
Thread.current["sshkit_backend"] = nil
1632
end
1733

1834
def initialize(host, &block)

Diff for: test/unit/backends/test_abstract.rb

+22
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,28 @@ def test_invoke_raises_no_method_error
131131
end
132132
end
133133

134+
def test_current_refers_to_currently_executing_backend
135+
backend = nil
136+
current = nil
137+
138+
backend = ExampleBackend.new do
139+
backend = self
140+
current = SSHKit::Backend.current
141+
end
142+
backend.run
143+
144+
assert_equal(backend, current)
145+
end
146+
147+
def test_current_is_nil_outside_of_the_block
148+
backend = ExampleBackend.new do
149+
# nothing
150+
end
151+
backend.run
152+
153+
assert_nil(SSHKit::Backend.current)
154+
end
155+
134156
# Use a concrete ExampleBackend rather than a mock for improved assertion granularity
135157
class ExampleBackend < Abstract
136158
attr_writer :full_stdout

0 commit comments

Comments
 (0)