How to do a safe join pathname in ruby?

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

I recommend using File.join

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

Solution 2 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJirapongView Question on Stackoverflow
Solution 1 - RubycsextonView Answer on Stackoverflow
Solution 2 - RubyDaniel Von FangeView Answer on Stackoverflow