Sha256: 07dce16119cad20623130538e569c8f953812fe5aefdcf2c203714069172890a

Contents?: true

Size: 1.64 KB

Versions: 2

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

require_relative './parent_element_for'
require_relative './split_text_at_target_word'

module ArticleFixtureGen
  module Data
    # Replaces the (INTERNAL!) list of child nodes of an element with a list
    # generated elsewhere (that replaces a single text node with two text nodes
    # separated by a new element).
    class ReplaceChildNodesUsingNewChild
      def self.call(parent_node, target_entry, new_el)
        new(parent_node, target_entry, new_el).call
      end

      def call
        element.instance_variable_set :@nodes, nodes
      end

      protected

      def initialize(parent_node, target_entry, new_el)
        @element = ParentElementFor.call(parent_node, target_entry.dom_position)
        @target_entry = target_entry
        @new_el = new_el
        self
      end

      private

      attr_reader :element, :new_el, :target_entry

      def leading_nodes
        element.nodes[leading_node_indexes]
      end

      def leading_node_indexes
        0...node_index
      end

      def node_index
        target_entry.dom_position.last
      end

      def nodes
        parts = SplitTextAtTargetWord.call(element, target_entry)
        replacement_nodes_for(parts)
      end

      def parts_and_element(parts)
        parts.insert 1, new_el
      end

      def replacement_nodes_for(parts)
        [leading_nodes, parts_and_element(parts), trailing_nodes].flatten(1)
      end

      def trailing_nodes
        element.nodes[trailing_node_indexes]
      end

      def trailing_node_indexes
        node_index + 1..-1
      end
    end # class ArticleFixtureGen::Data::ReplaceChildNodesUsingNewChild
  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/replace_child_nodes_using_new_child.rb
article_fixture_gen-0.1.1 lib/article_fixture_gen/data/replace_child_nodes_using_new_child.rb