Reputation: 1123
I am trying to write a method which will perform some file manipulations on the files existing on a server. For example: copy from source to destination, symlink a file, read a file, etc. Here I need to handle 2-scenarios i.e., server can be local or remote.
In remote server scenario, I am connecting to the server (using net/ssh) and then running shell commands using exec
method. And for local server, since I do not need to establish any connections I am using Ruby FileUtils
methods. I have pasted the piece of code for your reference.
I wanted to check if someone can suggest me to write this method more efficiently.
def create_link
begin
if self.particular_file_exists?
if [email protected]
@ssh.exec!("ln -s file1 file1-dump")
else
FileUtils.ln_sf("file1", "file1-dump")
end
end
rescue => e
$LOG.log(2, "Error occurred")
end
end
Upvotes: 0
Views: 77
Reputation: 35112
Just quick edit:
def create_link
return unless self.particular_file_exists?
if @ssh.local
FileUtils.ln_sf "file1", "file1-dump"
else
@ssh.exec! "ln -s file1 file1-dump"
end
rescue
$LOG.warn "Error occurred"
end
For deeper ideas you should ask https://codereview.stackexchange.com/
Upvotes: 1
Reputation: 230551
I can't say about performance optimizations, but here's what I think is a more maintainable/extensible code. You don't need all those local/remote branches in every goddamned method. Instead, extract environment specific behaviour into their own objects and delegate work to them. Something like this:
class FileManipulator
attr_reader :handler
def initialize(ssh)
@handler = ssh? RemoteHandler.new(ssh) : LocalHandler.new
end
def create_link
handler.create_link if handler.particular_file_exists?
rescue => e
$LOG.log(2, "Error occurred")
end
RemoteHandler = Struct.new(:ssh) do
def create_link
ssh.exec!("ln -s file1 file1-dump")
end
end
LocalHandler = Struct.new do
def create_link
FileUtils.ln_sf("file1", "file1-dump")
end
end
end
Upvotes: 2