Sha256: 6baa684ad9140fcaa32fa7775cb84f9f2df9f762abc45609f6fc47548d88abbb

Contents?: true

Size: 1.52 KB

Versions: 2

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true

module ArticleFixtureGen
  module Data
    # Produces an array of two strings such that, for a specified text node
    # (string), the first string will be the text before a specified word, and
    # the second (last) string will be the text after that word. The word in
    # question is specified by a child-node index relative to the `el` parameter
    # (an `Ox::Element` instance) and a word index within that child node.
    class SplitTextAtTargetWord
      def self.call(el, target_entry)
        new(el, target_entry).call
      end

      def call
        [head, tail]
      end

      protected

      def initialize(el, target_entry)
        @original_text = Internals.original_text(el, target_entry)
        @target_entry = target_entry
        @word_index = target_entry.word_index
        self
      end

      private

      attr_reader :original_text, :target_entry, :word_index

      def ends_in_space?
        original_text[-1] == ' '
      end

      def head
        words_in_range(0...word_index) + ' '
      end

      def tail
        ret = words_in_range(word_index..-1)
        ret += ' ' if ends_in_space?
        ret
      end

      def words_in_range(range)
        original_text.split[range].join(' ')
      end

      # Stateless methods.
      module Internals
        def self.original_text(el, target_entry)
          el.nodes[target_entry.dom_position.last]
        end
      end
      private_constant :Internals
    end # class ArticleFixtureGen::Data::SplitTextAtTargetWord
  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/split_text_at_target_word.rb
article_fixture_gen-0.1.1 lib/article_fixture_gen/data/split_text_at_target_word.rb