Skip to content

Instantly share code, notes, and snippets.

@dt1973
Last active August 29, 2015 14:17
Show Gist options
  • Save dt1973/96e5500b587c74fc3147 to your computer and use it in GitHub Desktop.
Save dt1973/96e5500b587c74fc3147 to your computer and use it in GitHub Desktop.

Fetching affiliate products in Rails with Delayed::Job and Ajax

Straight forward fetching products from the affiliate API takes up to 8 seconds which is intolerable.

Demo app: https://github.com/dt1973/ajax-affiliates

Problem

How to set up the callback?

app/controllers/main_controller.rb

class MainController < ApplicationController
  def index
    # Delay fetching
    @products = Affiliate.delay.fetch
  end
end

app/models/affiliate.rb

require "rest_client"

module Affiliate
  def self.fetch
    response = RestClient::Request.execute(
      :method => :get,
      :url => "http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=women&offset=0&limit=10"
    )

    @products = JSON.parse(response)["products"].map do |product|
      product = OpenStruct.new(product)
      product
    end
  end
end

app/views/main/index.html.erb

<h1>Products from affiliate API</h1>
<% if @products.any? %>
  <% @products.each do |product| %>
    <div class="product">
      <%= link_to product.name, product.url %>
    </div>
  <% end %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment