Skip to content

Commit

Permalink
Merge pull request #319 from mattbrictson/backend-thread-local
Browse files Browse the repository at this point in the history
Add SSHKit::Backend.current
  • Loading branch information
leehambley committed Jan 22, 2016
2 parents 67eb3a0 + 8032db6 commit 6c81f53
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ appear at the top.
[PR #308](https://github.com/capistrano/sshkit/pull/308) @mattbrictson
* `SSHKit::Backend::Printer#test` now always returns true
[PR #312](https://github.com/capistrano/sshkit/pull/312) @mikz
* Add `SSHKit::Backend.current` so that Capistrano plugin authors can refactor
helper methods and still have easy access to the currently-executing Backend
without having to use global variables.
[PR #319](https://github.com/capistrano/sshkit/pull/319) @mattbrictson

## 1.8.1

Expand Down
16 changes: 16 additions & 0 deletions lib/sshkit/backends/abstract.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ module Backend

MethodUnavailableError = Class.new(SSHKit::StandardError)

# The Backend instance that is running in the current thread. If no Backend
# is running, returns `nil` instead.
#
# Example:
#
# on(:local) do
# self == SSHKit::Backend.current # => true
# end
#
def self.current
Thread.current["sshkit_backend"]
end

class Abstract

extend Forwardable
Expand All @@ -12,7 +25,10 @@ class Abstract
attr_reader :host

def run
Thread.current["sshkit_backend"] = self
instance_exec(@host, &@block)
ensure
Thread.current["sshkit_backend"] = nil
end

def initialize(host, &block)
Expand Down
22 changes: 22 additions & 0 deletions test/unit/backends/test_abstract.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,28 @@ def test_invoke_raises_no_method_error
end
end

def test_current_refers_to_currently_executing_backend
backend = nil
current = nil

backend = ExampleBackend.new do
backend = self
current = SSHKit::Backend.current
end
backend.run

assert_equal(backend, current)
end

def test_current_is_nil_outside_of_the_block
backend = ExampleBackend.new do
# nothing
end
backend.run

assert_nil(SSHKit::Backend.current)
end

# Use a concrete ExampleBackend rather than a mock for improved assertion granularity
class ExampleBackend < Abstract
attr_writer :full_stdout
Expand Down

0 comments on commit 6c81f53

Please sign in to comment.