Module: Ensurance::HashEnsure::ClassMethods

Defined in:
lib/ensurance/hash_ensure.rb

Instance Method Summary collapse

Instance Method Details

#ensure(thing) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ensurance/hash_ensure.rb', line 13

def ensure(thing)
  case thing.class.name
  when 'NilClass'
    nil
  when 'Hash', 'HashWithIndifferentAccess'
    thing
  when 'String'
    JSON.parse(thing)
  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

#ensure!(thing) ⇒ Object

Raises:

  • (ArgumentError)


36
37
38
39
40
# File 'lib/ensurance/hash_ensure.rb', line 36

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