Sha256: f3c0d66367d72ce4db4bab2f8cb32ef30c60d7adb3e453074a2766717161dc17

Contents?: true

Size: 1.67 KB

Versions: 11

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

module Vedeu

  module Editor

    # Fetches an item from a collection.
    #
    # @api private
    #
    class Item

      # @param (see #initialize)
      # @return (see #by_index)
      def self.by_index(collection, index = nil)
        new(collection, index).by_index
      end

      # Returns a new instance of Vedeu::Editor::Item.
      #
      # @param collection [Vedeu::Editor::Line|Vedeu::Editor::Lines]
      # @param index [Fixnum]
      # @return [Vedeu::Editor::item]
      def initialize(collection, index = nil)
        @collection = collection
        @index      = index
      end

      # @return [String|Vedeu::Editor::Line]
      def by_index
        return nil unless collection

        if index_out_of_range?
          last_item

        elsif index_within_range?
          nth_item

        else
          first_item

        end
      end

      protected

      # @!attribute [r] collection
      # @return [Vedeu::Editor::Line|Vedeu::Editor::Lines]
      attr_reader :collection

      # @!attribute [r] index
      # @return [Fixnum]
      attr_reader :index

      private

      # @return [String|Vedeu::Editor::Line]
      def first_item
        collection[0]
      end

      # @return [String|Vedeu::Editor::Line]
      def last_item
        collection[-1]
      end

      # @return [String|Vedeu::Editor::Line]
      def nth_item
        collection[index]
      end

      # @return [Boolean]
      def index_out_of_range?
        index.nil? || index > collection.size
      end

      # @return [Boolean]
      def index_within_range?
        index > 0 && index <= collection.size
      end

    end # Item

  end # Editor

end # Vedeu

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
vedeu-0.8.32 lib/vedeu/editor/item.rb
vedeu-0.8.31 lib/vedeu/editor/item.rb
vedeu-0.8.30 lib/vedeu/editor/item.rb
vedeu-0.8.29 lib/vedeu/editor/item.rb
vedeu-0.8.28 lib/vedeu/editor/item.rb
vedeu-0.8.27 lib/vedeu/editor/item.rb
vedeu-0.8.26 lib/vedeu/editor/item.rb
vedeu-0.8.25 lib/vedeu/editor/item.rb
vedeu-0.8.24 lib/vedeu/editor/item.rb
vedeu-0.8.23 lib/vedeu/editor/item.rb
vedeu-0.8.22 lib/vedeu/editor/item.rb