Skip to content

Instantly share code, notes, and snippets.

@blainekasten
Last active September 11, 2020 12:39
Show Gist options
  • Save blainekasten/51a70eecea06874db3cb to your computer and use it in GitHub Desktop.
Save blainekasten/51a70eecea06874db3cb to your computer and use it in GitHub Desktop.
Mirroring Rails Environment in Javascript
// This should actually be a .js.erb file so you can interpolate Ruby code in it
// I left it off the file naming because the gist would color words weird when .js.erb
// was the file extension
;(function(window){
var _environment;
/*
* Namespace.
* You could name this anything you want, even stick to rails conventions and do:
*
* ```javascript
* window.Rails = {};
* Rails.env = function(){};
* ```
*
* It is important that this is a function. It gives us the option to attach other
* methods to it, while still impersonating a string
*
* @type Function !IMPORTANT
*/
window.Environment = function() {
// Have it return the toString function as we override that later
// to make it return the actual environment
return this.toString();
};
/*
* Our actual tracking of the environemnt variable.
* By making this a .js.erb file we can interpolate Ruby code and return the environment
* string
*
* @type String
*/
_environment = "<%= Rails.env %>";
/*
* Make the namespace function impersonate a string.
* This override of `prototype.toString` makes it so consoling window.Environment will print
* what we want, instead of the function definition
*/
Environment.toString = function() {
return environment;
};
/*
* HELPER FUNCTIONS
* Add any helper function you want for environment checks
*
* @return Boolean
*/
Environment.isProduction = function(){
return 'production' === environment;
};
Environment.isDevelopment = function(){
return 'development' === environment
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment