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 }

Parameters:

  • hash (Hash)

    The hash from which to pick the key/value pairs.

  • *keys (Array)

    The hash keys to exclude.

Returns:

  • (Hash)

    A new hash without the specified keys.



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 }

Parameters:

  • hash (Hash)

    The hash to modify.

  • *keys (Array)

    The hash keys to exclude.

Returns:



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 }

Parameters:

  • hash (Hash)

    The hash from which to pick the key/value pairs.

  • *keys (Array)

    The hash keys to include.

Returns:

  • (Hash)

    A new hash with only the selected keys.



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.

Parameters:

  • hash (Hash)

    The hash to convert.

Returns:

  • (Mash)

    The Mash for the specified hash.



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