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. Returnsnil
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:
Open /etc/launchd.conf file (e.g. $sudo nano /etc/launchd.conf)
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
Set other env variables for RubyMine if necessary
Save changes
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
Ruby 'Pg' Gem Linking to Wrong Copy of Libpq.5.Dylib (On Osx)
Best Practice to Mark Deprecated Code in Ruby
Extract Links (Urls), with Nokogiri in Ruby, from a Href HTML Tags
When Do We Use the "||=" Operator in Rails? What Is Its Significance
How to Find the Path a Ruby Gem Is Installed at (I.E. Gem.Lib_Path C.F. Gem.Bin_Path)
Force Bundle Install to Use Https:// Instead of Git:// for Github-Based Gems
Rails: Money Gem Converts All Amounts to Zero
Generate All Possibles Combinations of an Array with a Length Within a Given Range
Ruby Use Array Tvalues to Index Nested Hash of Hash
Cannot Click HTML Element with Watir
How to Build a Ruby Hash Out of Two Equally-Sized Arrays
How to List the Currently Available Objects in the Current Scope in Ruby
Can't Install Ffi -V '1.9.18' on MACos Catalina
How to Get Constants Defined by Ruby's Module Class via Reflection
How to Create a Delete Link for a Related Object in Ruby on Rails