Sha256: e1e8b6e7f00f0d19157d844631fa3a433a220793a9b5f87e1a7996a6f3cfae9c

Contents?: true

Size: 1.13 KB

Versions: 1

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

module Gitlab
  # Converts hashes to the objects.
  class ObjectifiedHash
    # Creates a new ObjectifiedHash object.
    def initialize(hash)
      @hash = hash
      @data = hash.each_with_object({}) do |(key, value), data|
        value = self.class.new(value) if value.is_a? Hash
        value = value.map { |v| v.is_a?(Hash) ? self.class.new(v) : v } if value.is_a? Array
        data[key.to_s] = value
      end
    end

    # @return [Hash] The original hash.
    def to_hash
      hash
    end
    alias to_h to_hash

    # @return [String] Formatted string with the class name, object id and original hash.
    def inspect
      "#<#{self.class}:#{object_id} {hash: #{hash.inspect}}"
    end

    def [](key)
      data[key]
    end

    private

    attr_reader :hash, :data

    # Respond to messages for which `self.data` has a key
    def method_missing(method_name, *args, &block)
      data.key?(method_name.to_s) ? data[method_name.to_s] : super
    end

    def respond_to_missing?(method_name, include_private = false)
      hash.keys.map(&:to_sym).include?(method_name.to_sym) || super
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gitlab-4.16.0 lib/gitlab/objectified_hash.rb