Created
December 21, 2016 06:21
-
-
Save semenyukdmitry/99f3b8b4fb970581c9fcaac8381d3176 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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