Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rails: HTTP Get request from Callback Method (in model)

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

Upvotes: 0

Views: 907

Answers (1)

zetetic
zetetic

Reputation: 47548

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.

Upvotes: 1

Related Questions