Skip to content

Instantly share code, notes, and snippets.

@jwo
Last active December 17, 2015 20:09
Show Gist options
  • Save jwo/5665325 to your computer and use it in GitHub Desktop.
Save jwo/5665325 to your computer and use it in GitHub Desktop.
Simple callback-esque way to calculate in the background, and have the result later on by storing a reference to it in the session
class CalculateTheThing
include Celluloid
def calculate
sleep 5
result = rand
yield(result) if block_given?
result
end
end
# id, result
class Calculation < ActiveRecord::Base
attr_accessible :result
end
class PagesController < ApplicationController
def dashboard
if session[:calculation_id].blank?
Calculation.create.tap do |calc|
CalculateTheThing.new.async.calculate do |result|
Calculation.find(calc.id).update_attributes(results: result)
end
session[:calculation_id] = calc.id
end
end
calculation = Calculation.find(session[:calculation_id])
@counter = calculation.result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment