Share Rails configuration to Javascript

Share Rails configuration to Javascript

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

or add the following line into Gemfile:

Configuration

In addition to default configuration variables:you should set values related to Javascript: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:

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:

Usage

For instance, you have config file global/hosts.yml with hosts settings for api and web:After that you have access to Global Javascript object with settings from global/hosts.yml file:And in production environment:

References

For more details, check out the source code and documentation on github.