Skip to content

Instantly share code, notes, and snippets.

@ruslan-oliinyk
Last active May 27, 2021 10:08
Show Gist options
  • Save ruslan-oliinyk/48c3fc7ad286cc30b43d98ea886ae4ba to your computer and use it in GitHub Desktop.
Save ruslan-oliinyk/48c3fc7ad286cc30b43d98ea886ae4ba to your computer and use it in GitHub Desktop.
How to use the same variables inside Ruby ​​and JS code at the same time

How to use the same variables inside Ruby and JS code at the same time

Prerequisites:

  • Ruby 2.3+
  • Rails 5.1+
  • Webpacker 4.x.x
  • Node.js 8.16.0+
  • Yarn 1.x+

Installation

*** Rails ***

Add dotenv gem to your application's Gemfile:

gem 'dotenv-rails'

Create a file called ".env" in the root of your project. Next, set up your variables with the format key=value, delimited by line breaks:

API_KEY="YOURAPIKEYGOESHERE"
SECRET_KEY="YOURSECRETKEYGOESHERE"

Finally, make sure the .env file is not committed to your repository. This can be achieved by opening (or creating) a .gitignore file and adding this line:

.env # This contains secrets, don't store in source control

*** Webpacker ***

Head to your terminal to install dotenv with your preferred package manager:

Using npm:

npm i dotenv

Using yarn:

yarn add dotenv

Add next lines to the "config/webpack/environment.js"

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
const dotenv  = require('dotenv')

dotenv.config({ path: '.env', silent: true })

environment.plugins.prepend('Environment', new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))))

module.exports = environment

Done!

You can then reference these variables in your JavaScript app code with process.env:

process.env.API_KEY // Compiles to "YOURAPIKEYGOESHERE"

in your Ruby code:

ENV['API_KEY'] # return "YOURAPIKEYGOESHERE"

Enjoy! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment