Ruby: Most Concise Way to Use an Env Variable If It Exists, Otherwise Use Default Value

Ruby: Most concise way to use an ENV variable if it exists, otherwise use default value

myvar = ENV['MY_VAR'] || 'foobar'

N.B. This is slightly incorrect (if the hash can contain the value nil) but since ENV contains just strings it is probably good enough.

Rails: difference between ENV.fetch() and ENV[]

The ENV hash-like object is plain Ruby, not part of Rails. From the fine ENV#[] manual:

Retrieves the value for environment variable name as a String. Returns nil if the named variable does not exist.

and the fine ENV#fetch manual:

Retrieves the environment variable name.

If the given name does not exist and neither default nor a block a provided an IndexError is raised. If a block is given it is called with the missing name to provide a value. If a default value is given it will be returned when no block is given.

So just like Hash#[] and Hash#fetch, the only difference is that fetch allows you to specify the behavior if a key is not found (use a default value passed to fetch, default block passed to fetch, or raise an exception) whereas [] just silently gives you nil if the key isn't found.

In the specific case of:

ENV.fetch("MY_VAR")
ENV['MY_VAR']

the difference is that ENV['MY_VAR'] will give you nil if there is no MY_VAR environment variable but ENV.fetch('MY_VAR') will raise an exception.

Concise way to set a default value?

If you want to set a default value for one key, Hash#fetch is your answer.

If passed a block, it will return the value of the block if the key isn't in the params.

params = {}
params.fetch(:foo) { 'default' }
=> "default"

If the default is easy to compute, you can just as well do this as a second argument in the method:

params = {}
params.fetch(:foo, 'default')
=> "default"

If you want to set a default for the whole hash, you should look into #default= and #default_proc. Since your question concerns params, I'm guessing you can't initialize the hash with an appropriate default.

BTW, your way will not return nil if the value is set to nil, but fetch will properly return nil.

params[:foo] = nil
params.fetch(:foo) { 'default' }
=> nil

Shell out from ruby while setting an environment variable

system({"MYVAR" => "42"}, "echo $MYVAR")

system accepts any arguments that Process.spawn accepts.

How to assign default value to variable if first condition failed?

The exact same idiom works (assuming by "failed" you mean opts.env is nil):

iex(1)> nil || "staging"
"staging"
iex(2)> "production" || "staging"
"production"

Elixir, as Ruby, treats nil as a falsy value.

Setup default Ruby variables in RubyMine

Jetbrains actually has a page to help you do just this:

Mac OS X applies .bash_profile and .profile only for Terminal.app environment and Apple's technical documentation suggests using ~/.MacOSX/environment.plist for other applications. So, by default PATH value will differ for RubyMine and the console.

MacOS 10.6 or later

We recommend to manage your environment variables using free
Enviroment Variables preference pane instead of environment.plist
manual editing.

MacOS < 10.6

Unfortunately, the "environment.plist" approach doesn't always work on
MacOS < 10.6, e.g if you start RubyMine from Spotlight the environment
is not applied.

Thus real solution is to set your environment variables in
/etc/launchd.conf (thanks to David Goudreau for this tip). For
detailed description please read Mac OS X Global Environment Variables
article.

So you should:

  1. Open /etc/launchd.conf file (e.g. $sudo nano /etc/launchd.conf)

  2. Then set correct PATH env variable

    setenv PATH /Users/romeo/.gem/ruby/1.8/bin:/opt/local/bin:/opt/local/sbin:/opt/local/libexec/git-core:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
  3. Set other env variables for RubyMine if necessary

  4. Save changes

  5. Reboot


P.S: If you always launch RubyMine using Dock or QuickSilver and do
not use Spotlight you can install Enviroment Variables preference pane
and use it instead of the manual environment.plist editing.

NB: Please don't miss "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
in the end of PATH value, because PATH=...:$PATH doesn't work here.

Configuring variables depending on current Rails.env

There's an awesome gem for just this, called rails_config: github repo

But if you just want to configure this and only this variable, you could create a constant at the environment configuration files that rails already has.

Something like:

In your config/environments/production.rb

# production.rb
Rails.configuration.my_awesome_changing_domain = "somedomain.me"

In your config/environments/development.rb

# development.rb
Rails.configuration.my_awesome_changing_domain = "stackoverflow.com"

In your config/environments/staging.rb

# staging.rb
Rails.configuration.my_awesome_changing_domain = "news.ycombinator.com"

Other methods to do that are discussed in another answers, at this thread:
https://stackoverflow.com/a/5053882

Best regards



Related Topics



Leave a reply



Submit