Jokingpsh Jokingpsh - 7 months ago 41
Ruby Question

Ruby double pipe usage

I have a file which have different paths for remote server and local server.

Remote server path:
"/app/public/front-end/public/JSONModels/IdPairing/Text.json"
Local server path:
"public/front-end/public/JSONModels/IdPairing/Text.json"


I basically wanna make sure my app finds correct path for the file regardless of which server I'm at.

So I found something like double pipe ( || ) in Ruby syntax like below:

File.read("/app/public/front-end/public/JSONModels/IdPairing/Text.json" || "public/front-end/public/JSONModels/IdPairing/Text.json")


But it seems like it only reads the first path. How do you make sure it reads the second path if the file is not being found in the first path?

Thanks

Answer

Why it doesn't work for you:

irb(main):001:0> File.read("some made up name") Errno::ENOENT: No such file or directory - some made up name from (irb):1:in `read' from (irb):1 from /usr/bin/irb:12:in `<main>' irb(main):002:0> File.read("some made up name" || "Gemfile") Errno::ENOENT: No such file or directory - some made up name from (irb):2:in `read' from (irb):2 from /usr/bin/irb:12:in `<main>'

As you can see, when you try to read a file that doesn't exist, Ruby explodes.

That's what exist? is for.

What you should do

irb(main):003:0> filename = File.exist?("some made up name") ? "some made up name" : "Gemfile" => "Gemfile" irb(main):004:0> File.read(filename)

That's one way to do it, at least.

Comments