How to use a Rails environment variable in Capistrano deploy script? - ruby-on-rails

If I have a constant in my Rails environment.rb, for example...
SOME_CONSTANT = 3
Is it possible to access this in my capistrano deploy.rb somehow? It seems simple but I can't figure out how.

This ended up working:
created a file config/initializers/my_constant.rb
put my constant in there (rails automatically loads files there so I can use the constant in my app)
then in deploy.rb added load 'config/initializers/my_constant' so it could be used there as well.

You should access it via the ENV[] hash (this is a Ruby thing), here is an example using the TERM environmental variable.
puts "Your Terminal is #{ENV['TERM']}"
If you need a ruby constant, from your rails environment, you should load it:
require 'config/environment'
Beware that this will load your whole application environment, you should think to use something like AppConfig, or SimpleConfig (insert other tool here) to store configurations, then you need only load the tool, which processes your config files.

Why not define these constants in a file in lib/ and then require the file in both your Rails app and your Capfile?

As the value is not only used by the rails app, I would probably store such configuration information in a language agnostic format (yaml, json, ini, xml) which can be easily parsed by different tools without fear of possible side effects.

Related

Rails adding translations to a running rails environment

Is there a way to manually inject a translation through the Rails console ?
Suppose I am working on a dev environment, and I want to test some code in a production console (eg to test some statistics on real data).Problem is, the code I want to test relies on new translations that didn't exist (or were changed) in the production environment.
So my code returns a lot of translation_missing
Can I inject the missing translations ? Via a hash or a YML file ?
I18n.load_translations(hash_or_file)
Usually Application instances that serve http requests (for example running under Unicorn/Puma) are not available via Rails console. When someone login to production server and type $RAILS_ENV=production rails c it starts another application process. Translations dictionary is a kind of in-memory cache and usually it is not possible to change that cache for/from another process (in general). You can reload translations only for application instance that started by Rails console, but not for running server.
Only one way to hot reload translations is adding kind of a hook into source code of application to re-read YAML file, but it seems better just restart application server.
UPDATE: For testing purposes I18n cache could be modified like:
I18n.backend.send(:translations)[:en][:date][:formats][:default] = "%Y-%Z"

Setting Test environment variables in rails without putting in source code

I'm using Twilio for an app and on production I set the auth token using heroku's CLI. I'm using sms-spec (https://github.com/monfresh/sms-spec) to test my app's Twilio integration locally. I want to set ENV['TWILIO_AUTH_TOKEN'] to my token in the test environment.
I use guard to auto-run my tests whenever I make changes so I don't want to have to manually set the ENV variable each time I run tests. I also don't want to put the token in my source code for security reasons.
Is there a way I can set the ENV variable for my local test environment such that it is permanent and not in my source? I've spent a few hours researching this and can't seem to find a good explanation of how to do this. Any help is much appreciated :)
Two approaches:
Use a gem like Dotenv (link). This is the approach I use in most of my applications for development. Simply include the gem in your gemfile, bundle install and then store any environment variable settings in a top level file called .env. Restart your rails server and ENV will be automatically loaded. Very easy to use and convenient.
If you are flexible on the ENV part, and you are running Rails 4.1+, you can use config/secrets/yml. This is documented very well in the Rails 4.1 release notes, Section 2.2. So, in your case, you would set it up like so:
development:
twilio_auth_token: verysecretstring
Then, in your initializer, instead of referencing ENV['TWILIO_AUTH_TOKEN'], you would use Rails.application.secrets.twilio_auth_token. I haven't tried this myself, but it is on my list as I would rather use native Rails functionality than a separate gem.
Of course, any files which contain your secrets needs to be safeguarded carefully. At a minimum, make sure you include in .gitignore so that your secrets do not find their way into your code respository.

Setting an appropriate environment to work

Here begins the road. I need to configure a working environment manageable and accessible. I've been reading a bit about environment variables. Windows have an easy configuration, as can be easily changed through window panes. In unix is different ...
export environment_variable = argument
eg. export DISPLAY = localhost: 0.0.
The question is: should I declare the environment variables when I install rvm? need to work with ruby, and not have to be writing the source myvar each time I start the console.
Same question for node and git.
Obviously I ask because in windows if I had to do, and I have unix doubt.
The short answer to your question is No. During the installation, setup and use of rvm, you will not be setting any environment-specific variables that relate to your application, nor for the rubies/gemsets/gems that rvm will be managing for you.
Once rvm is up and running, and you have installed at least one version of ruby (managed by rvm), there are a few options available to you for conveniently managing your environment variables.
a) You can use your unix shell config files (.bashrc, .bash_profile, etc.) to set env variables, but I don't recommend it. This is the equivalent of the Windows scenario you quoted in your question, but is not the common practice in the ruby-unix community.
b) If you are using Rails, environment-specific configurations can be managed in the source code itself, in environment files. For example, production.rb, development.rb, test.rb. etc.
c) If this is a Ruby codebase (i.e. no Rails) then, you can define your environment variables in an 'initializer' file, which can be invoked at the entry point of your ruby project. I typically put my application-specific variables in a yaml file like below.
In file: env_vars.yaml
---
:env_var_a: a.b.com
:env_var_b: 1111
:env_var_c: foo
:env_var_d: bar
To load these environment variables for use in your codebase,
require 'yaml'
env_vars = YAML.load(File.read(file_path('env_vars.yml')))
If you prefer to not use YAML, you can save the configs in a text file, and use ruby's native File class to access them. I like YAML because it easily creates a hash for me.
Regardless of which option you choose, there is no way you will need to type source every time you start a session

Use Ruby on Rails environment config based on URL/Machine Name

I have a RoR3 app with multiple environment configs, development.rb, test.rb and production.rb.
Is there a way I can instruct the application to used a specific config based on a value in the URL or machine name??
For instance if the machine name contains "dev", then use development.rb.
Edit
If that is not possible, is there a way I can access the request URL from the application.rb or environment.rb files maybe. If so, I could probably use a regex on the URL to determine and set the environment settings dynamically within if blocks.
In the end, we'll end up having many more than just 3 environments, all with certain differences. So I need a very flexible way to set the config.
Probably not. By the time the rails app is running (and can look at the machine name) it's already picked an environment. Unless you hack the boot script...
It'd be much easier to just put the environment into the startup-command-line for each machine.

Adding urls api keys in environment variable in ruby

I have a url that I am using in one of the controllers. Is there a better place to put this url? The url uses an API key and I was wondering if there is a better place to add this url and/or api key such that its not added in the controller class code and ergo more editable? If i add it as an environment variable or anything else how do i access it from my controller class? thank you. ITS A RUBY AND RAILS PROJECT
Using environment variables might be a good idea if you want to keep things like API keys and passwords out of your source code. Accessing them from within your code is done with the ENV object:
my_api_key = ENV['MY_API_KEY']
To use this technique, you need to set up the variables in your environment before launching your app, and how you do this depends on your local setup, and will likely also vary between development and production.
In development, you can simply set the environment vars in your shell, e.g. with bash:
$ export MY_API_KEY=foobar123abc
$ rails s
Now rails will start and have access to this environment variable. You can also set variables for just a single command:
$ MY_API_KEY=foobar123abc rails s
Depending on what the sevice/api is, you could set some of them to default development/test values in config/environments/development.rb (or test.rb):
ENV['MY_API_KEY'] = 'non_secret_api_key_that_can_be_shared_around'
Setting up environment variables in production will depend on how you're deploying your app. Phusion have an article on using environment variables in Passenger if your using that. There's also a useful article on using environment variables with Heroku which is worth a read even if you're not using them for deployment.
You can add it to application.rb file as
config.service {
:api_key => 'api_key'
}
Or better yet, add it to development.rb and production.rb files so that you can test it better.
You can access this api_key from controller like
Rails.application.config.service[:api_key]

Resources