Sha256: 4e0ffc8ed68162002e16717a887d55e448ccc29717f84ea75d27bba4beaa4b7c

Contents?: true

Size: 1.2 KB

Versions: 1

Compression:

Stored size: 1.2 KB

Contents

require 'tins/thread_local'

module Tins
  module HashSymbolizeKeysRecursive
    extend Tins::ThreadLocal

    thread_local :seen

    def symbolize_keys_recursive(circular: nil)
      self.seen = {}
      _symbolize_keys_recursive(self, circular: circular)
    ensure
      self.seen = nil
    end

    def symbolize_keys_recursive!(circular: nil)
      replace symbolize_keys_recursive(circular: circular)
    end

    private

    def _symbolize_keys_recursive(object, circular: nil)
      case
      when seen[object.__id__]
        circular != nil and object = circular
      when Hash === object
        seen[object.__id__] = true
        result = {}
        object.each do |k, v|
          result[k.to_s.to_sym] = _symbolize_keys_recursive(v, circular: circular)
        end
        if object.frozen?
          object = result
        else
          object.replace result
        end
      when Array === object
        seen[object.__id__] = true
        result = object.map do |v|
          _symbolize_keys_recursive(v, circular: circular)
        end
        if object.frozen?
          object = result
        else
          object.replace result
        end
      end
      object
    end
  end
end

require 'tins/alias'

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tins-1.22.1 lib/tins/hash_symbolize_keys_recursive.rb