Runify
Easily turn any object into a service
Presentation
This library provides a very simple interface for any 'runnable' object (responds to run) to be used as a service. When included into a class, the Runify module adds startup, shutdown and restart methods, which take care of wrapping execution of the run method into a thread.
Installation
Gemfile
gem 'runify'
Terminal
gem install -V runify
Usage
For any object that features a run method, simply include the Runify module into the class. Instances of this class will respond to the following new methods:
startup
Calling this method will spawn a new thread around the run method, effectively starting the service in the 'background'.
shutdown
Calling shutdown will request the service to terminate by setting @stop to true and wait for the thread to complete (join). Once this method returns, the service has completely terminated.
restart
The restart method is nothing more than a shortcut to shutdown and startup:
def restart
shutdown
startup
end
The @stop variable
Any class that includes the runify module should check the @stop instance variable in its run method. Runify will set @stop to true to indicate execution should end and the run method should return when a shutdown is requested.
A typical run method will usually be implemented as such:
def run
update until @stop
end
Examples
Runifying a simple service class
require 'runify'
# Foo Service
class FooService
# Runify
include Runify
def run
update until @stop
end
def update
# Business Logic goes here...
end
end
# Start Foo Service in the background
fs = FooService.new
fs.startup
puts 'Foo Service has started'
# Do something while service is running...
# Restart Foo Service
fs.restart
puts 'Foo Service has restarted'
# Do something while service is running...
# Shutdown Foo Service
fs.shutdown
puts 'Foo Service has terminated'
License
The gem is available as open source under the terms of the MIT License.