如何在 ruby 中做一个安全的连接路径名? [英] How to do a safe join pathname in ruby?
问题描述
我的 Rails 开发环境基于 Windows,我的生产环境基于 Linux.
My Rails development environment is Windows-based, and my production environment is Linux-based.
可能会使用 VirtualHost.假设需要在 /public
文件夹中使用 File.open('/tmp/abc.txt', 'r')
引用一个文件名.
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')
.
——但在 Windows 中它应该是 C:\tmp\abc.txt
.如何进行正确的路径连接来处理两种不同的环境?
—but in Windows it should be C:\tmp\abc.txt
. How can I do a correct path join to handle the two different environments?
prefix_tmp_path = '/tmp/'
filename = "/#{rand(10)}.txt"
fullname = prefix_tmp_path + filename # /tmp//1.txt <- but I don't want a double //
当 prefix_tmp_path = "C:\tmp\"
我得到 C:\tmp\/1.txt
处理这两种情况的正确方法是什么?
What is the correct way to handle both cases?
推荐答案
我推荐使用 File.join
I recommend using File.join
>> File.join("path", "to", "join")
=> "path/to/join"
这篇关于如何在 ruby 中做一个安全的连接路径名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!