Last active
December 17, 2015 20:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CalculateTheThing | |
include Celluloid | |
def calculate | |
sleep 5 | |
result = rand | |
yield(result) if block_given? | |
result | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# id, result | |
class Calculation < ActiveRecord::Base | |
attr_accessible :result | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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