Reputation: 359
I'm trying to load some items from this external API using REST Client and DelayedJob.
But, unlike Ajax check for database change using route, these items don't get saved to the database but rather go straight to the view -- so how would I know when they're done loading so I can load them into the client using Ajax?
Live app which you can run on the fly: http://runnable.com/VW9rQx-KiIFfmpII/ajax-affiliates
app/controllers/main_controller.rb
class MainController < ApplicationController
def index
# Delay fetching
@products = Affiliate.delay.fetch
end
# Pseudo-code from SO `ajax-check-for-database-change-using-route`
#
# def check_items_loaded
# @items_status = Affiliate.find(params[:id]).items_loaded
# respond_to do |wants|
# wants.js
# end
# end
end
config/routes.rb
# Pseudo-code from SO `ajax-check-for-database-change-using-route`
# get '/check_items_loaded/:id', to: 'photos#check_items_loaded', as: :check_items_loaded
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
# More pseudo-code
# Add `items_loaded` boolean to database?
# private
# def set_items_loaded
# self.update_attributes(items_loaded: ???)
# end
end
Upvotes: 0
Views: 599
Reputation: 3870
You might be able to hack together a solution using ActionController::Streaming. Do take into account potential session bottlenecks.
An alternate solution might be using Websockets & Redis.
Upvotes: 0
Reputation: 32758
You could look into a pub-sub architecture using something like PubNub[1] or Pusher[2]
Your front-end would subscribe to those endpoints and then you can have your backend publish events to those endpoints (which are then read from the consumers (your frontend))
[1] PubNub - http://www.pubnub.com/
[2] Pusher - https://pusher.com/
Upvotes: 1