Search code examples
javascriptruby-on-railsvariablesglobal-variables

Where/How to state global JS variables in Ruby on Rails 7?


I would like to state a global JavaScript variable for my Ruby on Rails 7 project. In Rails 5 I was used to state global JS variables in app/assets/javascripts/application.js like this:

// app/assets/javascripts/application.js (Rails 5)

var MY_GLOBAL_VAR = MY_GLOBAL_VAR || {};

... but in Rails 7 the directory app/assets/javascripts/ seems to be no longer used in favour of app/javascript/. In Rails 7, I tried to state global variables in files such as app/javascript/application.js (🙈) without success. I also tried to create the file app/assets/javascripts/application.js and state there the global variables without success.

In the browser's Console I always get the error:

Uncaught ReferenceError: MY_GLOBAL_VAR is not defined

Where/How can I state global JS variables in Rails 7?


Solution

  • What's about

    window.MY_GLOBAL_VAR = window.MY_GLOBAL_VAR || {}
    

    in the app/javascript/application.js

    Of course you need include this file in the top of application.html.erb