I have a constant within a JavaScript function that needs to take a value from a Rails controller or directly from a JSON endpoint.
Here is the controller action that returns the value that I need:
class EventsController < ApplicationController
def calendar
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
@calendar_list = service.list_calendar_lists.items
rescue Google::Apis::AuthorizationError
response = client.refresh!
session[:authorization] = session[:authorization].merge(response)
retry
end
This controller action has a corresponding JSON endpoint as well, localhost:3000/calendar.json:
This JavaScript is in my application.rb file. I tried passing my calendarList constant the instance variable @calendar_list but that didn't work.
function getEventSources(){
const calendarList = <%= @calendar_list %>
const keyArray = calendarList.map(cal => {
return 'googleCalendarId'
})
const calendarIds = calendarList.map(cal => {
return cal["id"]
})
eventSources = []
for(i=0; i < keyArray.length; i++) {
var obj = {}
obj[keyArray[i]] = calendarIds[i]
eventSources.push(obj);
}
return eventSources
};
This is my /calendar.json endpoint:
[
{
id: "en.usa#[email protected]",
summary: "Holidays in United States"
},
{
id: "nba_1_%41tlanta+%48awks#[email protected]",
summary: "Atlanta Hawks"
}
]
Do I need to make some type of AJAX call to retrieve this value or is there a simpler way?
I moved my javascript into a
html.erbfile and out ofapplication.jsThis is how I passed the controller value to my JavaScript constant
this did the trick.