如何在ruby中使用安全连接路径名?

时间:2022-09-24 23:33:21

My Rails development environment is Windows-based, and my production environment is Linux-based.

我的Rails开发环境是基于windows的,我的生产环境是基于linux的。

It's possible that VirtualHost will be used. Assume that one filename needs to be referenced in the /public folder with File.open('/tmp/abc.txt', 'r').

可能会使用虚拟主机。假设需要在/public文件夹中使用File.open('/tmp/abc)引用一个文件名。txt”、“r”)。

—but in Windows it should be C:\tmp\abc.txt. How can I do a correct path join to handle the two different environments?

-在Windows中应该是C:\tmp\abc.txt。如何做一个正确的路径连接来处理两个不同的环境?

prefix_tmp_path = '/tmp/'
filename = "/#{rand(10)}.txt"

fullname = prefix_tmp_path + filename # /tmp//1.txt <- but I don't want a double //

And when prefix_tmp_path = "C:\tmp\" I get C:\tmp\/1.txt

当prefix_tmp_path = "C:\tmp\"我得到C:\tmp\/1.txt

What is the correct way to handle both cases?

处理这两种情况的正确方法是什么?

2 个解决方案

#1


265  

I recommend using File.join

我建议使用File.join

>> File.join("path", "to", "join")
=> "path/to/join"

#2


39  

One thing to note. Ruby uses a "/" for file separator on all platforms, including Windows, so you don't actually need use different code for joining things together on different platforms. "C:/tmp/1.text" should work fine.

一件事需要注意。Ruby在所有平台(包括Windows)上都使用“/”作为文件分隔符,因此实际上不需要使用不同的代码将不同平台上的内容连接在一起。“C:/ tmp / 1。文本”可正常工作。

File.join() is your friend for joining paths together.

join()是将路径连接在一起的朋友。

prefix_tmp_path = 'C:/tmp'
filename = "#{rand(10)}.txt"
fullname = File.join(prefix_tmp_path, filename) # e.g., C:/tmp/3.txt

#1


265  

I recommend using File.join

我建议使用File.join

>> File.join("path", "to", "join")
=> "path/to/join"

#2


39  

One thing to note. Ruby uses a "/" for file separator on all platforms, including Windows, so you don't actually need use different code for joining things together on different platforms. "C:/tmp/1.text" should work fine.

一件事需要注意。Ruby在所有平台(包括Windows)上都使用“/”作为文件分隔符,因此实际上不需要使用不同的代码将不同平台上的内容连接在一起。“C:/ tmp / 1。文本”可正常工作。

File.join() is your friend for joining paths together.

join()是将路径连接在一起的朋友。

prefix_tmp_path = 'C:/tmp'
filename = "#{rand(10)}.txt"
fullname = File.join(prefix_tmp_path, filename) # e.g., C:/tmp/3.txt