Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zosiu/1b24690ba42cc032dea6 to your computer and use it in GitHub Desktop.
Save zosiu/1b24690ba42cc032dea6 to your computer and use it in GitHub Desktop.
Instagram Real Time Update w/ Rails
require 'active_job/retry'
class InstagramJob < ActiveJob::Base
include ActiveJob::Retry
variable_retry delays: [60, 2 * 60, 5 * 60, 15 * 60, 60 * 60]
queue_as :instagram_rtu
def perform(instagram_user_uid, instagram_media_uid)
user = User.find_by! instagram_uid: instagram_user_uid
media = user.instagram_media instagram_media_uid
# ... do your thing here
end
end
class InstagramRealTimeUpdatesController < ActionController::Base
def callback
case request.method_symbol
when :get
render text: Instagram.meet_challenge(params, ENV['INSTAGRAM_VERIFY_TOKEN'])
when :post
Instagram.process_subscription(request.body.read) do |handler|
handler.on_user_changed do |user_id, data|
media_id = (data['data'] || {})['media_id']
InstagramJob.perform_later user_id, media_id
end
end
head :ok
when :options
headers['Access-Control-Allow-Methods'] =
allowed_methods.map { |sym| sym.to_s.upcase }.join(', ')
head :ok
end
end
protected
def verify_request_type
head :method_not_allowed unless allowed_methods.include?(request.method_symbol)
end
def allowed_methods
[:get, :post]
end
end
Rails.application.routes.draw do
match 'instagram_real_time_update',
to: 'instagram_real_time_updates#callback',
via: [:get, :post]
end
class User < ActiveRecord::Base
def instagram_media(media_id)
instagram.media_item media_id
end
private
def instagram
@instagram ||= Instagram.client access_token: instagram_auth_token
end
end
@zosiu
Copy link
Author

zosiu commented May 19, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment