Boolean logic with Rails ENV variables
If you use Rails 5+, you can do ActiveModel::Type::Boolean.new.cast(ENV['MY_VARIABLE'])
.
In Rails 4.2, use ActiveRecord::Type::Boolean.new.type_cast_from_user(ENV['MY_VARIABLE'])
.
Documentation Rails 5+: https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
Environment Variables as the name suggests, are environment dependent variables which store different values for same keys based on the environment(production, staging, development) you working on.
e.g. it holds an Access_Key for some api which has sandbox mode and production mode. Thus, to make your code DRY and effective you set an environment variable to get that access_key of sandbox mode for development/staging and live key for production.
What you are trying to do is use them unlike the reason they are defined for, no doubt they can be used that way. Since they are constants what I recommend is doing the following.
create a constants.rb
file in your initializers containing
class Constant
BOOL_CONSTANT = ENV['MY_VARIABLE'].present?
# OR
BOOL_CONSTANT = ENV['MY_VARIABLE'] == 'true'
end
then you can use it anywhere you like. This way you can achieve what you want to but under the hood. ;)