Module: Rose::CoreExtensions

Included in:
ObjectAdapter
Defined in:
lib/rose/core_extensions.rb

Instance Method Summary collapse

Instance Method Details

#require_keys(hash, *required_keys) ⇒ Object

Validates that the given hash includes the required keys. If any keys are missing, ArgumentError will be raised.

Parameters:

  • hash (Hash)

    the hash to validate

  • required_keys (Array<Symbol>)

    the list of keys

Raises:

  • (ArgumentError)


9
10
11
12
# File 'lib/rose/core_extensions.rb', line 9

def require_keys(hash, *required_keys)
  missing_keys = required_keys - hash.keys
  raise ArgumentError, "Missing required key(s): #{missing_keys.join(', ')}" unless missing_keys.empty?
end

#required_values(hash, *required_keys) ⇒ Object

Returns the values of required keys in the given hash

Parameters:

  • hash (Hash)

    the hash to validate

  • required_keys (Array<Symbol>)

    the list of keys



19
20
21
22
23
24
25
# File 'lib/rose/core_extensions.rb', line 19

def required_values(hash, *required_keys)
  require_keys(hash, *required_keys)
  values = required_keys.inject([]) do |values, key|
    values << hash[key]
  end
  required_keys.length == 1 ? values.first : values
end