Leo
Leo

Reputation: 1

Ruby: File.open odd behavior with variable as name of file

Ruby Noob Here! I'm trying to create and write to files in ruby using variables as the name of the files to be created. If I use a type the file name it work same with another variable #{system}, but the issue appears to be with a specific variable that is parsed early on. Error received- Errno::ENOENT: No such file or directory

array#record contains: 
Sun /log/schedule.log.20180617
Mon /log/schedule.log.20180618  
Tue /log/schedule.log.20180619
Wed /log/schedule.log.20180620
Wed /log/schedule.log

Section of code.

lines = record.split("\n")
lines.each do |line|
    log = /(\/.*schedule.log(?:\.20[0-9]{6})?)/.match(line)
    @cmd = "grep DEBUG #{log} | grep \"start\\|running\""
    rawdata = ssh.exec!(@cmd) 
    logfile = File.new("#{system}_#{log}", 'w+')
       logfile.puts rawdata
    logfile.close
end
ssh.close  

OUTPUT Error received- Errno::ENOENT: No such file or directory - server1_schedule.log

Desired output should create a handful of log files with the naming convention <persystem_schedule.log<date>>.

Upvotes: 0

Views: 147

Answers (1)

Keith Bennett
Keith Bennett

Reputation: 4960

I'm pretty sure you're not giving sufficient information to solve the problem, but in these cases I find that it's often helpful to simplify the code; doing so often reveals other issues.

Is there a reason you're using the File open, puts, and close? This adds a lot of complexity which I think is unnecessary, and that complexity may be masking some other problem. I recommend changing this:

rawdata = ssh.exec!(@cmd) 
logfile = File.new("#{system}_#{log}", 'w+')
logfile.puts rawdata
logfile.close

to something like this:

File.write("#{system}_#{log}", ssh.exec!(@cmd))

and see if the result changes or if it reveals a different problem.

Upvotes: 1

Related Questions