4

I want to use an input path in the following code:

File.exists?(File.expand_path(path))

Can I use environment variables in path, and what should the syntax be?

3
  • Not clear what you mean. What path do you want? Do you mean load path? That is an array of directories. Commented Aug 24, 2015 at 9:40
  • Sorry for not being clear. Here's what I mean: let's say I have a environment variable MY_VAR and I'd like path to be %MY_VAR%/bin. This syntax doesn't work, and neither does $MY_VAR/bin. Is there a different syntax that should work? Commented Aug 24, 2015 at 9:45
  • ENV['MY_VAR'], Is this what you mean? Commented Aug 24, 2015 at 9:54

4 Answers 4

6

You can use standard ruby string interpolation (though it's a little bit wordy)

path = "log/#{ENV['RAILS_ENV']}.log" # or whatever
# >> "log/development.log"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is the only solution that works for me, because I can't modify the rest of the code, I can only play with the contents of path.
2

To expand environment variables, you should do it yourself:

def expand_env(str)
  str.gsub(/\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/) { ENV[$1] }
end

expand_env("${SHELL}:%USER%:$PAGER")
# => "/bin/bash:amadan:less"

(both Windows-style and Unix-style are supported, but only the basic substitution, and not any crazy stuff that bash is capable of).

Comments

1

For portability it is probably best to use File::join and ENV Hash:

File.exists?( File.join(ENV['MY_VAR'],'bin') )

Comments

0

Rubocop suggested the following improvements to the answer by @Amadan, and I added a check for nil.

def expand_env(str)
  return nil unless str

  str.gsub(/\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/) do 
    ENV.fetch(Regexp.last_match(1), nil) 
  end
end

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.