Sha256: 936645dd94f9c56c293f8d76f63c6c4a4441fb8347ee0cfc3cddb9aaf2e80bd6

Contents?: true

Size: 1011 Bytes

Versions: 2

Compression:

Stored size: 1011 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
        when "ActionController::UnfilteredParameters", "ActionController::Parameters"
          thing.permit!.to_h
        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

2 entries across 2 versions & 1 rubygems

Version Path
ensurance-0.1.6 lib/ensurance/hash_ensure.rb
ensurance-0.1.5 lib/ensurance/hash_ensure.rb