Initial situation: Each week a nested folder-/file-structure has to be created. Content is added to the files. Afterward the structure is copied to a shared-folder for long-time documentation.
Example:
The idea is now to write a script, which automates the folder-structure creation.
Here's what I have implemented:
require "date"
require "fileutils"
projects_path = "./reports/#{Time.now.strftime("%Y_%m_%d_%H_%M")}"
dir_paths = []
dir_paths << projects_path
["alpha", "beta", "gamma"].each do |name|
dir_paths << "#{projects_path}/team_#{name}"
end
if Dir.exist? projects_path
puts "#{projects_path} does already exist.\nExiting."
exit true
else
FileUtils.mkdir_p dir_paths
dir_paths[1...(dir_paths.length)].each do |path|
FileUtils.touch [
"#{path}/logs.txt",
"#{path}/notes.txt" ]
end
puts "Created directory '#{projects_path}' successfully."
end
- Could my implementation become improved?
- Would you have chosen a complete different approach, for implementing the solution? How would you have done it?
1 Answer 1
Only a few notes:
- Creating
dir_paths
as an empty array, then on the next line immediately appendingprojects_path
to it seems odd vs. just adding it immediately. dir_paths[1...(dir_paths.length)]
is equivalent todir_paths[1..-1]
With these changes:
require "date"
require "fileutils"
projects_path = "./reports/#{Time.now.strftime("%Y_%m_%d_%H_%M")}"
dir_paths = [project_paths]
["alpha", "beta", "gamma"].each do |name|
dir_paths << "#{projects_path}/team_#{name}"
end
if Dir.exist? projects_path
puts "#{projects_path} does already exist.\nExiting."
exit true
else
FileUtils.mkdir_p dir_paths
dir_paths[1..-1].each do |path|
FileUtils.touch [
"#{path}/logs.txt",
"#{path}/notes.txt" ]
end
puts "Created directory '#{projects_path}' successfully."
end
Given that if projects_path
already exists, the program exits immediately, you could elide the else
entirely.
require "date"
require "fileutils"
projects_path = "./reports/#{Time.now.strftime("%Y_%m_%d_%H_%M")}"
dir_paths = [project_paths]
["alpha", "beta", "gamma"].each do |name|
dir_paths << "#{projects_path}/team_#{name}"
end
if Dir.exist? projects_path
puts "#{projects_path} does already exist.\nExiting."
exit true
end
FileUtils.mkdir_p dir_paths
dir_paths[1..-1].each do |path|
FileUtils.touch [
"#{path}/logs.txt",
"#{path}/notes.txt" ]
end
puts "Created directory '#{projects_path}' successfully."
It's also possible to distill:
projects_path = "./reports/#{Time.now.strftime("%Y_%m_%d_%H_%M")}"
dir_paths = [project_paths]
["alpha", "beta", "gamma"].each do |name|
dir_paths << "#{projects_path}/team_#{name}"
end
Down to the more declarative following code.
projects_path = "./reports/#{Time.now.strftime("%Y_%m_%d_%H_%M")}"
dir_paths = [
project_paths,
*["alpha", "beta", "gamma"].map { |name|
"#{projects_path"}/team_#{name}"
}
]