Skip to content

Instantly share code, notes, and snippets.

@jnstq
Created March 22, 2009 12:49
Show Gist options
  • Save jnstq/83154 to your computer and use it in GitHub Desktop.
Save jnstq/83154 to your computer and use it in GitHub Desktop.
class User
def initialize()
@context = Context.new
end
def state
@context.state
end
end
class Context
attr_accessor :state
def initialize
@state = Pending.new(self)
end
end
class State
attr_accessor :name
def initialize(context)
@context = context
@name = self.class.name.downcase.to_sym
end
def to_s
name
end
end
class Pending < State
def active!
@context.state = Active.new(@context)
end
end
class Active < State
def inactive!
@context.state = Inactive.new(@context)
end
end
class Inactive < State
def delete!
@context.state = Delete.new(@context)
end
end
class Delete < State
def pending!
@context.state = Pending.new(@context)
end
end
if __FILE__ == $PROGRAM_NAME
require "rubygems"
require "spec"
describe User do
before(:each) do
@user = User.new
end
it "should have initial state" do
@user.state.name.should eql(:pending)
end
it "should transform to new state" do
@user.state.active!
@user.state.name.should eql(:active)
end
it "should not allow invalid transition" do
@user.state.delete!
@user.state.name.should eql(:pending)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment