Skip to content

Instantly share code, notes, and snippets.

@semenyukdmitry
Created December 21, 2016 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save semenyukdmitry/99f3b8b4fb970581c9fcaac8381d3176 to your computer and use it in GitHub Desktop.
Save semenyukdmitry/99f3b8b4fb970581c9fcaac8381d3176 to your computer and use it in GitHub Desktop.
module TestState
InvalidStateError = Class.new(RuntimeError)
def get_state stately
Object.const_get("TestState::#{stately.state}").new stately
rescue NameError
raise InvalidStateError, "Invalid State '#{stately.state}'"
end
ACTIONS = [:start, :stop]
ACTIONS.each do |action|
define_method action do
get_state(self).public_send action
end
end
class Base
def initialize stately
@stately = stately
end
TestState::ACTIONS.each do |action|
define_method action do
raise InvalidStateError, "Can't #{action} from '#{@stately.state}'"
end
end
end
class New < Base
def start
@stately.state = 'Start'
end
end
class Start < Base
def stop
@stately.state = 'Stop'
end
end
class Stop < Base
end
end
class Foo
attr_accessor :state
include TestState
def initialize
@state = "New"
end
end
foo = Foo.new
p foo.state
foo.start
p foo.state
begin
foo.start
rescue
p "State Exception"
end
p foo.state
foo.stop
p foo.state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment