HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyMinor

Small script to re-create a file indefinitely

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptfilecreateindefinitelysmall

Problem

I created a small ruby script at work to recreate a text file I use for a test in the Java application we are supporting.

I'm still really new to the ruby paradigm and wanted to know if that small script respect most of the spirit of it.

The content of the file doesn't need to make sense since the only requirement I have is that a file exist.

Since I'm doing my test every minute mostly, I set the sleeping time between checking the existence of the file to 30 seconds.

require 'pathname'

PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30

path_to_text_file = Pathname.new(PATH)
while (true)
  unless path_to_text_file.exist? then
    File.open(PATH, "w") {|f| f.write("test") }
    puts "File #{PATH} created"
  end
  puts "Sleeping for #{SLEEP_TIME} seconds"
  sleep(SLEEP_TIME)
end


Could I do better? I'm on Windows and using JRuby, is there something I'm missing with my code being portable ?

Obvisously, I could make the path an argument of my script, but I don't need this at the moment.

Solution

Unless you really want to reinvent the wheel, you could use FileUtils.touch for this:


FileUtils.touch


Updates modification time (mtime) and access time (atime) of file(s) in list. Files are created if they don’t exist.

For example:

require 'fileutils'

PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30

loop do
  FileUtils.touch(PATH)
  sleep(SLEEP_TIME)
end

Code Snippets

require 'fileutils'

PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30

loop do
  FileUtils.touch(PATH)
  sleep(SLEEP_TIME)
end

Context

StackExchange Code Review Q#136669, answer score: 5

Revisions (0)

No revisions yet.