234

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 Answers 2

397

I recommend using File.join

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

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.