0

I want to create a callback in my User model. after a user is created, a callback is initiated to run get_followers to get that users twitter followers (via full contact API).

This is all a bit new to me...

Is this the correct approach putting the request in a callback or should it be in the controller somewhere? And then how do I make the request to the endpoint in rails, and where should I be processing the data that is returned?

EDIT... Is something like this okay?

User.rb

require 'open-uri'
require 'json'

class Customer < ActiveRecord::Base
  after_create :get_twitter

  private

  def get_twitter
    source = "url-to-parse.com"
    @data = JSON.parse(JSON.load(source))
  end

1 Answer 1

1

A few things to consider:

  • The callback will run for every Customer that is created, not just those created in the controller. That may or may not be desirable, depending on your specific needs. For example, you will need to handle this in your tests by mocking out the external API call.
  • Errors could occur in the callback if the service is down, or if a bad response is returned. You have to decide how to handle those errors.
  • You should consider having the code in the callback run in a background process rather than in the web request, if it is not required to run immediately. That way errors in the callback will not produce a 500 page, and will improve performance since the response can be returned without waiting for the callback to complete. In such a case the rest of the application must be able to handle a user for whom the callback has not yet completed.
Sign up to request clarification or add additional context in comments.

2 Comments

Can you point me in the right direction on how to make the callback code run in the background after the request is complete? That sounds ideal. thanks
Start here: edgeguides.rubyonrails.org/active_job_basics.html. Then you'll need to pick a backend, like Sidekiq or Resque.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.