How do I move this controller code to a Resque job?
I want to move some of my sessions controller process into a Resque worker to make logging in much smoother. I want to move parts from here:
def create
auth = request.env["omniauth.auth"]
omniauth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth,开发者_JAVA百科omniauth)
session[:user_id] = user.id
session['fb_auth'] = request.env['omniauth.auth']
session['fb_access_token'] = omniauth['credentials']['token']
session['fb_error'] = nil
@graph = Koala::Facebook::GraphAPI.new(current_user.token)
current_user.profile = @graph.get_object("me")
current_user.likes = @graph.get_connections("me", "likes")
current_user.friends = @graph.get_connections("me", "friends")
current_user.save
redirect_to root_url
end
Into a Resque worker (is it in /tasks?)
#ResqueFacebook.rb
require 'resque-retry'
Class FBResque
def self.perform()
@graph = Koala::Facebook::GraphAPI.new(current_user.token)
current_user.profile = @graph.get_object("me")
current_user.likes = @graph.get_connections("me", "likes")
current_user.friends = @graph.get_connections("me", "friends")
current_user.save
end
End
What do I add to the sessions controller to initialize that worker job? Also, because it won't exist in the session anymore, current_user will be a nil object. Would that mean the code in the worker would have to be in a for user in User loop?
I tend to put them in app/jobs/
, since it's on the autoload path, while lib
tends to be more of a nuisance (albeit it completely valid).
This should be enough:
require 'resque-retry'
class FBConnectionsJob
@queue = :fb_connections
def self.perform(user_id)
user = User.find(user_id)
graph = Koala::Facebook::GraphAPI.new(user.token)
user.profile = graph.get_object("me")
user.likes = graph.get_connections("me", "likes")
user.friends = graph.get_connections("me", "friends")
user.save
end
end
def create
auth = request.env["omniauth.auth"]
omniauth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth,omniauth)
session[:user_id] = user.id
session['fb_auth'] = request.env['omniauth.auth']
session['fb_access_token'] = omniauth['credentials']['token']
session['fb_error'] = nil
Resque.enqueue(FBConnectionsJob, current_user.id)
redirect_to root_url
end
PS: Why are you typing Class
and End
in uppercase? o_O
精彩评论