The usual way of storing Rails configuration data are YAML files. In one of our previous posts, we talked about proper way of dealing with Rails configuration.
Nowadays, Javascript applications built on top of RESTful API are common practice, and in cases like this configuration data might be duplicated across frontend and backend. We’ve faced this issue in our projects too and decided to extend our global gem to make access to Rails configuration from Javascript.
Installation
gem install global
or add the following line into Gemfile
:
gem 'global', '~> 0.1'
Configuration
In addition to default configuration variables:
Global.configure do |config| config.environment = "YOUR_ENV_HERE" config.config_directory = "PATH_TO_DIRECTORY_WITH_FILES" end
you should set values related to Javascript:
Global.configure do |config| config.namespace = "JAVASCRIPT_OBJECT_NAME" # default Global config.except = ["LIST_OF_FILES_TO_EXCLUDE_ON_FRONT_END"] # default :all config.only = ["LIST_OF_FILES_TO_INCLUDE_ON_FRONT_END"] # default [] end
All files are excluded by default due to security reasons.
WARNING!!! Don not include files that contain protected information – like api keys or credentials – because they will be accessible from the Browser console.
Require global file in application.js
:
/* = require global-js */
Advanced Configuration
In case you need different configurations for different parts of your application, you should create files manually.
If your application has admin
and application
namespace:
# app/assets/javascripts/admin/global.js.erb <%= Global.generate_js(namespace: "AdminSettings", only: %w(admin hosts)) %> # app/assets/javascripts/admin.js.coffee #= require admin/global
# app/assets/javascripts/application/global.js.erb <%= Global.generate_js(namespace: "AppSettings", except: %w(admin credentials)) %> # app/assets/javascripts/application.js.coffee #= require application/global
Usage
For instance, you have config file global/hosts.yml
with hosts settings for api and web:
development: web: localhost api: api.localhost production: web: myhost.com api: api.myhost.com
After that you have access to Global
Javascript object with settings from global/hosts.yml
file:
Global.hosts.web => "localhost"
And in production environment:
Global.hosts.web => "myhost.com"
References
For more details, check out the source code and documentation on github.