0

I have a few methods doing this:

def method_a
    Net::SSH.start(...) do |ssh|
    end
end

def method_b
    Net::SSH.start(...) do |ssh|
    end
end
def method_c
    Net::SSH.start(...) do |ssh|
    end
end

Each methods call Net::SSH start which are individual SSH sessions, doing different things.

Is there a way to reuse Net::SSH session so that all 3 methods utilize a single session?

THanks.

Gavin Yap
  • 642
  • 12
  • 26

3 Answers3

0

Yes, definitely you can make it DRY.

You can add one method which accept hostname for the Net::SSH connection as below:

def ssh_exec(hostname)

  Net::SSH.start( hostname, 'user', :timeout => 5, :paranoid => false ) do |ssh|

   ....
  end
end

Then you can call this method ssh_exec() with proper hostname wherever you need it...

Dev.rb
  • 487
  • 6
  • 14
  • thanks but I re-edit my question to be clearer. your solution doesn't work since each methods ssh block runs different stuff. Also its not about making code DRY, its about reusing the SSH session for all 3 sessions – Gavin Yap Jan 09 '19 at 05:09
0

The way to go in Net::SSH is to put

@ssh_session = Net::SSH.start( @host, nil, option={:config => true})

to a variable and then on each methods

def method_a
    @ssh_session.exec!("Hello a")
end

def method_b
     @ssh_session.exec!("Hello b")
end
def method_c
     @ssh_session.exec!("Hello c")
end

And of course i place all the above in a class, so that I can initialize and start a ssh session and exec commands without re-establishing SSH.

Gavin Yap
  • 642
  • 12
  • 26
0

Outside a class, you can try:


def call
  Net::SSH.start(...) do |ssh|
    method_a(ssh)
    method_b(ssh)
    method_c(ssh)
  end
end

def method_a(ssh)
  ssh.exec(...) 
end

def method_b(ssh)
   ssh.exec(...)
end

def method_c(ssh)
   ssh.exec(...)
end
If it's in a class, you can define `attr_reader :ssh` and then initialize it thus:
attr_reader :ssh

def initialize
  @ssh ||= Net::SSH.start(...)
end

With that, you can simply define

def method_a
  ssh.exec(...)
end

Same applies for other methods. I hope this helps?

ydaniju
  • 400
  • 4
  • 11
  • @ydanjiu, ur second method, in a class is what I've already answered. but for the first method. the call calls all 3 methods which is not what I wanna achieve. – Gavin Yap Jan 10 '19 at 02:07