Sha256: eb1cbea0e7aee5f68b252e8d1af5bebc96a16c07dad99b3adf245a7ff7f26905

Contents?: true

Size: 1.11 KB

Versions: 7

Compression:

Stored size: 1.11 KB

Contents

module StateMachina
  class StatesCollection
    include Enumerable

    def initialize(states)
      @states = states
    end

    def each(&block)
      if block_given?
        @states.each(&block)
      else
        to_enum(:each)
      end
    end

    def find_by_name(state_name)
      find do |state|
        state.name == state_name.to_s
      end
    end

    def before(state_name)
      to_a[..(index_by_name(state_name) - 1)]
    end

    def before_inclusive(state_name)
      to_a[..index_by_name(state_name)]
    end

    def past(state_name)
      to_a[(index_by_name(state_name) + 1)..]
    end

    def past_inclusive(state_name)
      to_a[index_by_name(state_name)..]
    end

    def between(from_state_name, to_state_name)
      to_a[index_by_name(from_state_name)...index_by_name(to_state_name)]
    end

    def between_inclusive(from_state_name, to_state_name)
      to_a[index_by_name(from_state_name)..index_by_name(to_state_name)]
    end

    private

    def index_by_name(name)
      listed_by_name.index(name.to_s)
    end

    def listed_by_name
      @listed_by_name ||= map(&:name)
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
state_machina-0.1.6 lib/state_machina/states_collection.rb
state_machina-0.1.5 lib/state_machina/states_collection.rb
state_machina-0.1.4 lib/state_machina/states_collection.rb
state_machina-0.1.3 lib/state_machina/states_collection.rb
state_machina-0.1.2 lib/state_machina/states_collection.rb
state_machina-0.1.1 lib/state_machina/states_collection.rb
state_machina-0.1.0 lib/state_machina/states_collection.rb