Вот пример, с которого можно начать. Я изменил ваши тестовые файлы в форму ExampleA_Bob
, чтобы упростить получение идентификатора.
Для тестирования просто поместите file_testing.rb
и file_owner.rb
в папку и запустите ruby file_testing.rb
. Он создаст тестовые файлы, а также скопирует их в папки для каждого пользователя в зависимости от того, разрешено ли ему просматривать их.
file_testing.rb
require "fileutils"
require_relative "file_owner"
# -----------------------------------------------------------------------------
# ---Helper Functions----------------------------------------------------------
# -----------------------------------------------------------------------------
def create_test_files(directory_for_files, file_names)
FileUtils.mkdir_p(directory_for_files)
file_names.each{ |file_name|
out_file = File.new("#{directory_for_files}#{file_name}", "w")
out_file.puts("Testing #{file_name}")
out_file.close
}
end
def create_file_owners(file_owner_permissions, path_to_files)
file_owners = []
file_owner_permissions.each{ |owner_name, owner_permissions|
file_owners.push(FileOwner.new(owner_name.to_s, owner_permissions, path_to_files))
}
return file_owners
end
def parse_file_identifier(file_name)
split_name = file_name.split("_")
return split_name[-1]
end
def sort_files(file_owners, path_to_files)
Dir.foreach(path_to_files) do |file|
next if file == "." or file == ".."
next if File.directory?(path_to_files + file)
file_owners.each{ |owner|
file_identifier = parse_file_identifier(file)
owner.copy_file_if_allowed(path_to_files + file, file_identifier)
}
end
end
# -----------------------------------------------------------------------------
# ---Main----------------------------------------------------------------------
# -----------------------------------------------------------------------------
path_to_files = "./test_files/"
file_names = ["ExampleA_Bob", "ExampleB_Bob", "ExampleC_Bob", "ExampleA_Harry", "ExampleB_Harry", "ExampleC_Harry", "ExampleA_Tom", "ExampleB_Tom", "ExampleC_Tom", "ExampleA_Steve", "ExampleB_Steve", "ExampleC_Steve"]
create_test_files(path_to_files, file_names)
file_owner_permissions = {
"Bob": ["Harry"],
"Harry": ["Bob", "Tom"],
"Tom": ["Harry", "Steve"],
"Steve": ["Tom"]
}
file_owners = create_file_owners(file_owner_permissions, path_to_files)
sort_files(file_owners, path_to_files)
file_owner.rb
require 'fileutils'
class FileOwner
attr_accessor :name
attr_accessor :permissions
def initialize(name, permissions, path_to_files)
@name = name
@permissions = permissions.push(name)
@personal_folder = path_to_files + name
ensure_personal_folder_exists()
end
public
def copy_file_if_allowed(file_path, file_identifier)
if @permissions.include? file_identifier
add_file_to_personal_folder(file_path)
end
end
private
def ensure_personal_folder_exists()
FileUtils.mkdir_p(@personal_folder)
end
def add_file_to_personal_folder(file_path)
FileUtils.cp(file_path, @personal_folder)
end
end