Sha256: a6826b26b41223191212d564072c9d7b9f63ca642bcd7f8946ed06bdc1d17e3c

Contents?: true

Size: 1.25 KB

Versions: 8

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaUtils
    class ToHash
      module ClassMethods
        def call(value)
          case value
          when Array then array_to_hash(value)
          when Hash then hash_to_hash(value)
          when NilClass, FalseClass then nil_to_hash(value)
          when String then string_to_hash(value)
          when Symbol then symbol_to_hash(value)
          else raise SeregaError, "Cant convert #{value.class} class object to hash"
          end
        end

        private

        def array_to_hash(values)
          return Serega::FROZEN_EMPTY_HASH if values.empty?

          values.each_with_object({}) do |value, obj|
            obj.merge!(call(value))
          end
        end

        def hash_to_hash(values)
          return Serega::FROZEN_EMPTY_HASH if values.empty?

          values.each_with_object({}) do |(key, value), obj|
            obj[key.to_sym] = call(value)
          end
        end

        def nil_to_hash(_value)
          Serega::FROZEN_EMPTY_HASH
        end

        def string_to_hash(value)
          symbol_to_hash(value.to_sym)
        end

        def symbol_to_hash(value)
          {value => Serega::FROZEN_EMPTY_HASH}
        end
      end

      extend ClassMethods
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
serega-0.6.1 lib/serega/utils/to_hash.rb
serega-0.6.0 lib/serega/utils/to_hash.rb
serega-0.5.2 lib/serega/utils/to_hash.rb
serega-0.5.1 lib/serega/utils/to_hash.rb
serega-0.5.0 lib/serega/utils/to_hash.rb
serega-0.4.0 lib/serega/utils/to_hash.rb
serega-0.3.0 lib/serega/utils/to_hash.rb
serega-0.2.0 lib/serega/utils/to_hash.rb