Question

While practicing Ruby, I decided it would be nice to have some sort of state machine gem to help me manage the application state of a basic Ruby app (not using Rails).

I didn't find one, or didn't know where to look. So I wrote one.

Was it helpful?

Solution

The gem's name is gk-application, it's on rubygems and the GitHub repo is here: https://github.com/gregkrsak/gk-application

Basically, an application is an instance of GK::Application, which can then be in one of four states: :stopped, :starting, :running or :stopping.

The application's code lives in the event handlers attached to each state. To start the app, set its state attribute to :starting.

If you have the gem installed and would prefer to have a project template built for you, simply use one of the following methods:

Using ruby:

ruby -e 'require "gk-application"' -e 'GK::Application.new.project'

Using irb:

$ irb
irb(main):001:0> require 'gk-application'
=> true
irb(main):002:0> GK::Application.new.project
=> nil
irb(main):003:0> quit

Either of which will generate a file named my_app.rb in the current directory, containing:

#!/usr/bin/env ruby

require 'gk-application'


my_app = GK::Application.new


my_app.on_starting = Proc.new do
  puts 'Starting.'
  my_app.state = :running
end

my_app.on_running = Proc.new do
  puts 'Running.'
  my_app.state = :stopping
end

my_app.on_stopping = Proc.new do
  puts 'Stopping.'
  my_app.state = :stopped
end

my_app.on_stopped = Proc.new do
  puts 'Stopped.'
end


my_app.state = :starting

Which should get you started. Thanks for reading! Feel free to contribute to the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top