跟踪每个用户的当前目录

时间:2015-05-18 22:58:22

标签: ruby

我目前正在创建一个客户端/服务器应用程序,它试图通过将其唯一标识符(用户名)和新的Dir对象配对到如下所示的哈希数组来跟踪多个连接用户的当前目录:

users = []
user = {:user => "userN", :dir => Dir.new(".")}
users.push(user)
...

虽然在用户哈希中访问目录密钥时,我似乎无法正确使用对象方法。

例如:

users[0][:dir].chdir("../")

返回undefined method chrdir for #<Dir:.>

同样,方法entries应该接受1个参数来列出目录的内容,只接受0个参数,当用0参数调用时,它只列出在创建Dir时初始化的当前目录。 / p>

是否有一种简单的方法可以跟踪用户在文件系统中的伪位置?

编辑::我找到了Pathname类,它实现了我需要的东西。我现在只是想知道在使用它时是否有更简洁的方法来实现cdls命令。

#Simulate a single users default directory starting point
$dir = Pathname.pwd

#Create a backup of the current directory, change to new directory, 
#test to see if the directory exists and if not return to the backup
def cd(dir)
        backup = $dir
        $dir += dir
        $dir = backup if !($dir.directory?)
end

#Take the array of Pathname objects from entries and convert them 
#to their string directory values and return the sorted array
def ls(dir)
        $dir.entries.map { |pathobject| pathobject.to_s }.sort
end

2 个答案:

答案 0 :(得分:0)

你的问题实际上并没有错误地使用哈希,Dir.chdir是一个改变当前进程工作目录的全局方法。 Dir.entries类似。

如果您尝试按用户跟踪路径,可以将其存储为File,也可以是目录。也就是说,目录表示为File,因此即使它被称为“文件”,它仍然可以存储目录路径。

答案 1 :(得分:0)

我发现问题的答案是使用Pathname类:Pathname

它允许您使用+=运算符来横向文件系统,尽管您必须手动执行许多检查以确保实际存在的横向位置。

当我实现我的ls命令时,我只是映射了Pathname.entries的输出,并对结果进行了排序。

def ls(pathname)
    pathname.entries.map { |pathobject| pathobject.to_s }.sort
end

这为您提供了一个排序字符串数组,其中包含当前目录中Pathname设置为的所有文件。

对于cd,您需要确保该目录存在,如果没有恢复到以前的好目录。

def cd(pathname, directory_to_move_to)
    directory_backup = pathname
    pathname += directory_to_move_to
    pathname = directory_backup if !(pathname.directory?)
end

使用示例:

my_pathname = Pathname.pwd
cd(my_pathname, "../")
ls(my_pathname)
相关问题