The Spaghetti Refactory Established 2015

One simple way to get data from a Rails view into a JavaScript file

I had a tricky problem where there was some data from the server that was being sent to the view in query params, and I needed it in my JS file to selectively show/hide elements. Here's what I ended up doing.

In my view (HAML syntax, for the uninitiated), I am essentially creating an empty div, giving it a unique ID, and filling in data attributes with the data I need. (NOTE: start_date, start_time, and time_zone are variables defined elsewhere):
  #video-or-in-person-fields{ 'data-start-date' => start_date, 'data-start-time' => start_time, 'data-time-zone' => time_zone }

Then, in my JS file:

start_date = $("#video-or-in-person-fields").attr('data-start-date')
start_time = $("#video-or-in-person-fields").attr('data-start-time')
time_zone = $("#video-or-in-person-fields").attr('data-time-zone')