Sha256: 2973a2ff367c47d5847d046f1778b3f79a247daf87de2d8f92755266128b0761

Contents?: true

Size: 1.14 KB

Versions: 4

Compression:

Stored size: 1.14 KB

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, "Unhandled Type for Hash to ensure: #{thing.class}"
            end
          else
            raise ArgumentError, "Unhandled Type for Hash to ensure: #{thing.class}"
          end
        end
      end

      def ensure!(thing)
        result = self.ensure(thing)
        raise ArgumentError, "Cannot Hash.ensure(#{thing})" unless result
        result
      end
    end
  end
end

::Hash.prepend(Ensurance::HashEnsure)

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ensurance-0.1.15 lib/ensurance/hash_ensure.rb
ensurance-0.1.14 lib/ensurance/hash_ensure.rb
ensurance-0.1.13 lib/ensurance/hash_ensure.rb
ensurance-0.1.12 lib/ensurance/hash_ensure.rb