#Celluloid
A Celluloid cell runs in its own thread and uses fibers to pass messages asynchronously.
##Types of Cells
###Future Cells One type of cell are called a futures. A future runs a block of code inside the cell. If you ask for a future value before it's ready the cell will lock to you until it can return the value. When you ask for future value that is already ready the cell will return the value right away.
require 'celluloid'
#=> true
election_results = Celluloid::Future.new do
sleep 30
['Obama wins.', 'Romney wins.'].sample
end
#=> #<Celluloid::Future:0x007f93b4969228>
election_results.ready?
#=> false
election_results.value # The value isn't ready so it synchronously locks.
# About 30 seconds later the cell returns: #=> "Obama wins."
election_results.ready? # It has been over 30 seconds now.
#=> true
election_results.value
#=> "Obama Wins."
###Class Cells Another type of cell is a class cell. A class cell is created by including Celluloid in a regular Ruby class. The cell instance methods can be called synchronously or asyncronously. When a cell method is called asynchronously it returns nil right away and runs the method inside the cell.
require 'celluloid'
#=> true
class Sleepy
include Celluloid # This include is all it takes to make a Celluloid cell.
def fizz_buzz n
sleep 0.1 # making the FizzBuzz sleepy!
result = if n % 15 == 0
'FizzBuzz'
elsif n % 3 == 0
'Fizz'
elsif n % 5 == 0
'Buzz'
else
n
end
puts result
end
end
#=> nil
sleepy = Sleepy.new
#=> #<Celluloid::Actor(Sleepy:0x3fd2e91742f0)>
Calling the cell method synchronously like normal takes about ten seconds:
1.upto 100 do |n|
sleepy.fizz_buzz n
end
Calling the cell method asynchronously takes only tenths of a secoond:
1.upto 100 do |n|
sleepy.async.fizz_buzz n
end
Checkout Celluloid at: https://github.com/celluloid/celluloid/blob/master/README.md