Sha256: 3d27d8c0dc1d660bb13e5872968ee83459976ba9795d189f0cccb2cf53082734

Contents?: true

Size: 1.03 KB

Versions: 3

Compression:

Stored size: 1.03 KB

Contents

require 'forwardable'
require 'state_pattern/state'

module StatePattern
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def initial_state_class
      @initial_state_class
    end

    def set_initial_state(state_class)
      @initial_state_class = state_class
      include ::StatePattern::Delegation
    end
  end

  module Delegation
    extend Forwardable

    def self.included(base)
      def_delegators :current_state_instance, *base.initial_state_class.state_methods
    end
  end

  def current_state_instance
    set_state if @current_state_instance.nil?
    @current_state_instance
  end

  def set_state(state_class = self.class.initial_state_class)
    return @current_state_instance if @current_state_instance.class == state_class
    @current_state_instance = state_class.new(self, @current_state_instance)
  end

  def transition_to(next_state_class)
    current_state_instance.exit
    set_state(next_state_class)
  end
end

require 'state_pattern/active_record' if defined? ActiveRecord::Base

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
state_pattern-2.0.2 ./lib/state_pattern.rb
state_pattern-2.0.1 ./lib/state_pattern.rb
state_pattern-2.0.0 ./lib/state_pattern.rb