217
votes

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 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?

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?

2

2 Answers

373
votes

I recommend using File.join

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

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.

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

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