Class: Gastly::Utils::Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/gastly/utils/hash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Hash

Returns a new instance of Hash.



6
7
8
# File 'lib/gastly/utils/hash.rb', line 6

def initialize(hash = {})
  @hash = hash.to_h
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



4
5
6
# File 'lib/gastly/utils/hash.rb', line 4

def hash
  @hash
end

Instance Method Details

#assert_valid_keys(*valid_keys) ⇒ Object

Validates all keys in a hash match *valid_keys, raising ArgumentError on a mismatch.

Note that keys are treated differently than HashWithIndifferentAccess, meaning that string and symbol keys will not match.

{ name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
{ name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
{ name: 'Rob', age: '28' }.assert_valid_keys(:name, :age)   # => passes, raises nothing


19
20
21
22
23
24
25
26
# File 'lib/gastly/utils/hash.rb', line 19

def assert_valid_keys(*valid_keys)
  valid_keys.flatten!
  hash.each_key do |k|
    unless valid_keys.include?(k)
      fail ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}")
    end
  end
end