Skip to content

Instantly share code, notes, and snippets.

@kopylovvlad
Created April 4, 2018 16:56
Show Gist options
  • Save kopylovvlad/96b1bf95bb6149c2589da953c6f7aed7 to your computer and use it in GitHub Desktop.
Save kopylovvlad/96b1bf95bb6149c2589da953c6f7aed7 to your computer and use it in GitHub Desktop.
class AbstractState
def initialize(content)
@content = content
end
def status
raise 'does not implement error'
end
def publish
raise 'does not implement error'
end
def go_back
raise 'does not implement error'
end
def render
raise 'does not implement error'
end
end
class Document
attr_accessor :content
def initialize(content)
@content = content
@state = DraftState.new(self)
end
def status
@state.status
end
def publish
@state.publish
end
def render
@state.render
end
def change_state(state)
@state = state
end
end
class DraftState < AbstractState
def publish
@content.change_state(ModerateState.new(@content))
end
def status
:draft
end
def render
''
end
def go_back
self
end
end
class ModerateState < AbstractState
def publish
@content.change_state(PublishedState.new(@content))
end
def status
:moderate
end
def render
''
end
def go_back
@content.change_state(DraftState.new(@content))
end
end
class PublishedState < AbstractState
def publish
self
end
def status
:published
end
def render
@content.content
end
def go_back
@content.change_state(ModerateState.new(@content))
end
end
d = Document.new('<p>Hello</p>')
# document with DraftState
d.status
# :draft
d.render
# ''
d.publish
# document with ModerateState
d.status
# :moderate
d.render
# ''
d.publish
# document with PublishedState
d.status
# :published
d.render
# '<p>Hello</p>'
d.publish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment