Tutorial :How to do a safe join pathname in ruby?



Question:

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?


Solution:1

I recommend using File.join

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


Solution:2

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  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »