I have a rails app and I'm trying to call the methods below from the controller, but I get this error:
undefined local variable or method "service" for #<EventsController:0x007fb6d27da1c8>` for this line: `api_method: service.freebusy.query
What's the problem here? Why can't the get_busy_events see the service var if it's defined above it?
controller
include GoogleCalendarApi
.....
@user = current_user
@google = @user.socials.where(provider: "google_oauth2").first
unless @google.blank?
@client = init_google_api_calendar_client(@google)
@result = open_gcal_connection(get_busy_events, @client, @google)
lib/google_api_calendar.rb
def init_google_api_calendar_client(google_account)
#method only called if google_oauth2 social exists
client = Google::APIClient.new
client.authorization.access_token = google_account.token
client.authorization.client_id = ENV['GOOGLE_API_KEY']
client.authorization.client_secret = ENV['GOOGLE_API_SECRET']
client.authorization.refresh_token = google_account.refresh_token
return client
end
def open_gcal_connection(options, initialized_client, social_object)
client = initialized_client
old_token = client.authorization.access_token
service = client.discovered_api('calendar', 'v3')
result = client.execute(options) #after execution you may get new token
# update token if the token that was sent back is expired
new_token = client.authorization.access_token
if old_token != new_token
social_object.update_attribute(token: new_token)
end
return result
end
def get_busy_events
result = open_gcal_connection(
api_method: service.freebusy.query,
body: JSON.dump({ timeMin: '2015-12-24T17:06:02.000Z',
timeMax: '2013-12-31T17:06:02.000Z',
items: social_object.email }),
headers: {'Content-Type' => 'application/json'})
#handling results
end
serviceit treats it as a method ofEventControllerbecause it is not defined inside the method it is called from. Default rails behaviour is to treat that as a method. if you are calling theservicethat is declared in theopen_gcal_connection, I suggest you declare it in theget_busy_eventsactionopen_gcal_connectionas one of its(open_gcal_connection) arguments. I don't know if that is intentional or not, but it looks sketchy