0

Is it possible to access Rails.env somehow directly through javascript/jQuery?

I could put something in the DOM and then read it, but that seems a bit hackish. Specifically, I'd like to be able to make a conditional statement in the javascript based on whether the environment is testing, development, staging, or production.

2 Answers 2

5

Rails is on the server. jQuery is on the client. You must somehow supply the information from the server to the client. The typical way is outputting a bit of JavaScript using server-side code, like so:

<script>
var environment = "<%= Rails.env %>";
</script>

...assuming the value won't have double quotes in it. Rails presumably has an equivalent to PHP's json_encode you could use if necessary.

Sign up to request clarification or add additional context in comments.

3 Comments

That was my understanding as well, was hoping maybe there was another way. Thanks for the confirmation!
@MikeCampbell: Similar, not quite the same (rather more limited in scope). But would do the job here!
0

Turns out this is possible without reading from the DOM; the solution for me was to insert the environment variable into the js file before precompilation.

Change myfile.js.coffee to myfile.js.coffee.erb and then insert with Ruby same as in a view, etc:

environment = "<%= Rails.env %>"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.