Sha256: 7ac8587649e76b089e466916f814a5370d8b42d32a7d2cdc55dc7ae8a23618ec

Contents?: true

Size: 996 Bytes

Versions: 1

Compression:

Stored size: 996 Bytes

Contents

# frozen_string_literal: true

module Dotpath
  class Walk
    def self.walk(obj, &block)
      case obj
      when Hash
        hash(obj, path: '', &block)
      when Array
        array(obj, &block)
      else
        obj
      end
    end

    def self.hash(obj, path: DELIMITER, &block)
      obj.each do |key, value|
        new_path = [path, Dotpath.encode(key)].join(DELIMITER)
        case value
        when Hash
          hash(value, path: new_path, &block)
        when Array
          array(value, path: new_path, &block)
        else
          yield(new_path, value)
        end
      end
    end

    def self.array(obj, path: DELIMITER, &block)
      index = 0
      obj.each do |value|
        new_path = "#{path}[#{index}]"
        case value
        when Hash
          hash(value, path: new_path, &block)
        when Array
          array(value, path: new_path, &block)
        else
          yield(new_path, value)
        end

        index += 1
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dotpath-0.1.0 lib/dotpath/walk.rb