Ruby – How to do a safe join pathname in ruby


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

It's possible that VirtualHost will be used. Assume that one filename needs to be referenced in the /public folder with'/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?

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

What is the correct way to handle both cases?

Best Solution

I recommend using File.join

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