Class: Hash

Inherits:
Object show all
Defined in:
lib/deployable/patch/hash/keys.rb,
lib/deployable/patch/hash/accept.rb,
lib/deployable/patch/hash/except.rb

Overview

Make testing for multiple keys easiers on a hash

Instance Method Summary collapse

Instance Method Details

#accept(*key_list) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/deployable/patch/hash/accept.rb', line 9

def accept(*key_list)
  r = self.class.new
  key_list.each{ |key| 
    begin
      r[key] = fetch(key)
    rescue KeyError

    end
  }
  r

  # Slower
  #dup.accept!(*key_list)
end

#accept!(*key_list) ⇒ Object

Removes any keys not given from the hash.

@hash.accept! :one, :two



28
29
30
31
32
# File 'lib/deployable/patch/hash/accept.rb', line 28

def accept!(*key_list)
  intersection = keys - key_list
  intersection.each{ |key| delete(key) }
  self
end

#except(*keys) ⇒ Object

Return a hash that includes everything but the given keys. This is useful for limiting a set of parameters to everything but a few known toggles:

@person.update_attributes(params[:person].except(:admin))

If the receiver responds to +convert_key+, the method is called on each of the arguments. This allows +except+ to play nice with hashes with indifferent access for instance:

=> 1.with_indifferent_access.except(:a) # => {} => 1.with_indifferent_access.except("a") # => {}



14
15
16
# File 'lib/deployable/patch/hash/except.rb', line 14

def except(*keys)
  dup.except!(*keys)
end

#except!(*keys) ⇒ Object

@hash.except! :one, :two



22
23
24
25
# File 'lib/deployable/patch/hash/except.rb', line 22

def except!(*keys)
  keys.each { |key| delete(key) }
  self
end

#has_all_keys?(*keys) ⇒ Boolean

Returns:

  • (Boolean)


5
6
7
# File 'lib/deployable/patch/hash/keys.rb', line 5

def has_all_keys? *keys
  keys.all? do |key| has_key?(key) end
end

#has_any_keys?(*keys) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/deployable/patch/hash/keys.rb', line 9

def has_any_keys? *keys
  keys.any? do |key| has_key?(key) end
end