Title photo
frugal technology, simple living and guerrilla large-appliance repair
Thu, 09 Nov 2017

Overcoming a permission error while using Ruby to move files

I'm not sure if this is a Windows-specific problem (I am currently developing on Windows 10), but part of the Ruby script in my Blog Poster app allows the user to "archive" all of the text files created as blog/social posts by moving them from the main program directory to an archives directory. I could opt not to create files at all, or have the script continue to overwrite the same one for each post.

But for now I'm keeping all of the text files (which the script creates and names based on the <title> tag of URLs that are part of the post, and I have an option to move those text files to the archive directory:

Dir.glob("*.txt") {|f| FileUtils.move File.expand_path(f), "archive" }

This part of the Ruby script worked fine when I started it and was doing nothing else, but if I used it to create one or more files, invoking the "archive" feature would error out and kill the script, saying that there was a permission issue.

Laziness. I looked in Stack Overflow and found the solution, which consisted of adding :force => true to the expression:

Dir.glob("*.txt") {|f| FileUtils.move File.expand_path(f), "archive", :force => true }

Now I can create posts (and their matching .txt files, which my blog uses) and then archive them at any point without the permission error killing the script. Thanks, Stack Overflow user mudasobwa.

Update: This modification allowed the script to keep running, but any files created during the current session are NOT moved to the archive directory.

The reason the files created during the session were not deletable is due to the script reading them out in the console. I will figure out a way to provide this output without rendering the files "undeletable" via Ruby.

Here are the lines I am removing for now:

puts "This is your file:\n\n"
File.open( @yourFileName ).each do |line|
   puts line
end