Sha256: efee7c4eea7592945cb5b1671843e697df67f000598103bdfb9a9ab48b9c953a

Contents?: true

Size: 896 Bytes

Versions: 3

Compression:

Stored size: 896 Bytes

Contents

# NOTE: https://blog.daveallie.com/clean-monkey-patching/

require 'active_support/core_ext/hash'
require 'json'

module Ensurance
  module HashEnsure
    def self.prepended(base)
      base.singleton_class.prepend(ClassMethods)
    end

    module ClassMethods
      def ensure(thing)
        case thing.class.name
        when "Hash","HashWithIndifferentAccess"
          thing
        when "String"
          JSON.parse(thing)
        when "NilClass"
          nil
        else
          if thing.respond_to?(:to_h)
            begin
              thing.to_h
            rescue TypeError
              raise ArgumentError.new("Unhandled Type for Hash to ensure: #{thing.class}")
            end
          else
            raise ArgumentError.new("Unhandled Type for Hash to ensure: #{thing.class}")
          end
        end
      end
    end
  end
end

::Hash.prepend( Ensurance::HashEnsure )

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ensurance-0.1.4 lib/ensurance/hash_ensure.rb
ensurance-0.1.3 lib/ensurance/hash_ensure.rb
ensurance-0.1.2 lib/ensurance/hash_ensure.rb