Module: DataMapper::Ext::Hash

Defined in:
lib/dm-core/support/ext/hash.rb

Class Method Summary collapse

Class Method Details

.except(hash, *keys) ⇒ Hash

Returns a hash that includes everything but the given keys.

Examples:

hash = { :one => 1, :two => 2, :three => 3 }
Ext::Hash.except(hash, :one, :two) # => { :three => 3 }


33
34
35
# File 'lib/dm-core/support/ext/hash.rb', line 33

def self.except(hash, *keys)
  self.except!(hash.dup, *keys)
end

.except!(hash, *keys) ⇒ Hash

Removes the specified keys from the given hash.

Examples:

hash = { :one => 1, :two => 2, :three => 3 }
Ext::Hash.except!(hash, :one, :two)
hash # => { :three => 3 }


50
51
52
53
# File 'lib/dm-core/support/ext/hash.rb', line 50

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

.only(hash, *keys) ⇒ Hash

Creates a hash with only the specified key/value pairs from hash.

Examples:

hash = { :one => 1, :two => 2, :three => 3 }
Ext::Hash.only(hash, :one, :two) # => { :one => 1, :two => 2 }


15
16
17
18
19
# File 'lib/dm-core/support/ext/hash.rb', line 15

def self.only(hash, *keys)
  h = {}
  keys.each {|k| h[k] = hash[k] if hash.has_key?(k) }
  h
end

.to_mash(hash) ⇒ Mash

Converts the specified hash to a Mash.



61
62
63
64
65
# File 'lib/dm-core/support/ext/hash.rb', line 61

def self.to_mash(hash)
  h = Mash.new(hash)
  h.default = hash.default
  h
end