Sha256: 7b27c87c5f8160f1d6df6d8973f67777b40edd01711b6351765a9f0b8793ebbd

Contents?: true

Size: 1.86 KB

Versions: 4

Compression:

Stored size: 1.86 KB

Contents

# frozen_string_literal: true

require 'i18n/tasks/data/tree/traversal'
module I18n::Tasks::Data::Tree
  # A list of nodes
  class Nodes
    include Enumerable
    include Traversal

    attr_reader :list

    def initialize(opts = {})
      @list = opts[:nodes] ? opts[:nodes].to_a.clone : []
    end

    delegate :each, :present?, :empty?, :blank?, :size, :to_a, to: :@list

    def to_nodes
      self
    end

    def attributes
      {nodes: @list}
    end

    def derive(new_attr = {})
      attr = attributes.except(:nodes, :parent).merge(new_attr)
      node_attr = new_attr.slice(:parent)
      attr[:nodes] ||= @list.map { |node| node.derive(node_attr) }
      self.class.new(attr)
    end

    def to_hash(sort = false)
      (@hash ||= {})[sort] ||= begin
        if sort
          self.sort { |a, b| a.key <=> b.key }
        else
          self
        end.map { |node| node.to_hash(sort) }.reduce({}, :deep_merge!)
      end
    end

    delegate :to_json, to: :to_hash
    delegate :to_yaml, to: :to_hash

    def inspect
      if present?
        map(&:inspect) * "\n"
      else
        Term::ANSIColor.dark '{∅}'
      end
    end

    # methods below change state

    def remove!(node)
      @list.delete(node) or raise "#{node.full_key} not found in #{self.inspect}"
      dirty!
      self
    end

    def append!(other)
      @list += other.to_a
      dirty!
      self
    end

    def append(other)
      derive.append!(other)
    end

    alias << append

    def merge!(nodes)
      @list += nodes.to_a
      dirty!
      self
    end
    alias + merge!

    def children(&block)
      return to_enum(:children) { map { |c| c.children ? c.children.size : 0 }.reduce(:+) } unless block
      each do |node|
        node.children.each(&block) if node.children?
      end
    end

    alias children? any?

    protected
    def dirty!
      @hash = nil
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
i18n-tasks-0.9.6 lib/i18n/tasks/data/tree/nodes.rb
i18n-tasks-0.9.5 lib/i18n/tasks/data/tree/nodes.rb
i18n-tasks-0.9.4 lib/i18n/tasks/data/tree/nodes.rb
i18n-tasks-0.9.3 lib/i18n/tasks/data/tree/nodes.rb