Sha256: 41f1e88d0ec5a915927c1b22d0a6134f79242f9e6e3f72400e5e318cd0318e35

Contents?: true

Size: 983 Bytes

Versions: 3

Compression:

Stored size: 983 Bytes

Contents

require 'forwardable'
require 'taketo/support'

module Taketo
  module Support

    class NamedNodesCollection
      include Enumerable
      extend Forwardable

      def_delegators :@nodes, :each, :length, :size, :empty?, :first, :last

      def initialize(nodes = [])
        @nodes = nodes
      end

      def push(node)
        @nodes << node unless find_by_name(node.name)
        self
      end
      alias :<< :push

      def [](index)
        if index.is_a?(Symbol)
          node = find_by_name(index) or raise KeyError, "Element with name #{index} not found"
          return node
        end
        @nodes[index] or raise KeyError, "Element ##{index} not found"
      end

      def find_by_name(name)
        @nodes.detect { |n| n.name == name }
      end

      def ==(other)
        return true if other.equal?(self)
        @nodes == other.is_a?(NamedNodesCollection) ? other.nodes : other
      end

      protected

      attr_reader :nodes
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
taketo-0.3.1 lib/taketo/support/named_nodes_collection.rb
taketo-0.3.0 lib/taketo/support/named_nodes_collection.rb
taketo-0.2.0 lib/taketo/support/named_nodes_collection.rb