Sha256: 79a265be76bfc3ccf4f24d820bc90f905f12a04a32a8b88ab6898da749acc517

Contents?: true

Size: 1.64 KB

Versions: 2

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

require_relative './build_word_list'

module ArticleFixtureGen
  module Data
    # Builds a word list suitable for randomly selecting MTP locations; these
    # may be used for either single- or paired-marker tag pairs by the simple
    # expedient of reverse-sorting the returned list of entries. Existing MTPs
    # in the content will be unaffected, as they will be treated as any other
    # element node and, since they have no contained text, will not affect the
    # result.
    class BuildTargetEntryList
      def self.call(parent_node, count)
        new(parent_node, count).call
      end

      def call
        entries.sort.reverse
      end

      protected

      def initialize(parent_node, count)
        @parent_node = parent_node
        @count = count
        @word_list = nil
        @chosen_indexes = []
        self
      end

      private

      attr_reader :chosen_indexes, :count, :parent_node

      def add_index(index)
        chosen_indexes << index
        index
      end

      def entries
        Array.new(count) { item_from_word_list }
      end

      def index_taken?(index)
        return true if index.to_i.zero? # covers nil
        chosen_indexes.include?(index)
      end

      def item_from_word_list
        word_list[random_index]
      end

      def random_index
        add_index random_index_value
      end

      def random_index_value
        index = rand(word_list.count) while index_taken?(index)
        index
      end

      def word_list
        @word_list ||= BuildWordList.call(parent_node: parent_node)
      end
    end # class ArticleFixtureGen::Data::BuildTargetEntryList
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
article_fixture_gen-0.1.2 lib/article_fixture_gen/data/build_target_entry_list.rb
article_fixture_gen-0.1.1 lib/article_fixture_gen/data/build_target_entry_list.rb