Sha256: 1c9c7ead3fc180aba0cb067ea9aebe3a171f9900ae38f18b30c665aa0b360115

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

# frozen_string_literal: true

module Micro::Attributes
  module Utils
    module Hashes
      def self.stringify_keys(arg)
        hash = Kind::Of.(::Hash, arg)

        return hash if hash.empty?
        return hash.transform_keys(&:to_s) if hash.respond_to?(:transform_keys)

        hash.each_with_object({}) { |(key, val), memo| memo[key.to_s] = val }
      end

      def self.symbolize_keys(arg)
        hash = Kind::Of.(::Hash, arg)

        return hash if hash.empty?
        return hash.transform_keys(&:to_sym) if hash.respond_to?(:transform_keys)

        hash.each_with_object({}) { |(key, val), memo| memo[key.to_sym] = val }
      end

      def self.keys_as(type, hash)
        return Kind::Of.(::Hash, hash) unless type

        return symbolize_keys(hash) if type == Symbol
        return stringify_keys(hash) if type == String

        raise ArgumentError, 'first argument must be the class String or Symbol'.freeze
      end

      def self.get(hash, key)
        value = hash[key.to_s]

        value.nil? ? hash[key.to_sym] : value
      end
    end

    module ExtractAttribute
      def self.call(object, key:)
        return object.public_send(key) if object.respond_to?(key)

        Hashes.get(object, key) if object.respond_to?(:[])
      end

      def self.from(object, keys:)
        Kind::Of.(::Array, keys).each_with_object({}) do |key, memo|
          memo[key] = call(object, key: key)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
u-attributes-2.3.0 lib/micro/attributes/utils.rb