Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SSHKit::Backend.current #319

Merged
merged 1 commit into from
Jan 22, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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