Class: Hash

Inherits:
Object show all
Defined in:
lib/garcon/core_ext/hash.rb

Overview

Author: Stefano Harding <[email protected]> License: Apache License, Version 2.0 Copyright: © 2014-2015 Stefano Harding

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Defined Under Namespace

Classes: UndefinedPathError

Instance Method Summary collapse

Instance Method Details

#argumentize(args_field = nil) ⇒ Object

Turn a hash into a method arguments.

h = { :list => [1,2], :base => "HI" }

Without an argument field.

h.argumentize #=> [ { :list => [1,2], :base => "HI" } ]

With an argument field.

h.argumentize(:list)   #=> [ 1, 2, { :base => "HI" } ]
h.argumentize(:base)   #=> [ "HI", { :list => [1,2] } ]


34
35
36
37
38
39
40
41
42
43
# File 'lib/garcon/core_ext/hash.rb', line 34

def argumentize(args_field = nil)
  config = dup
  if args_field
    args = [config.delete(args_field)].flatten.compact
  else
    args = []
  end
  args << config
  return args
end

#capitalize_keysHash

Returns a new hash with all keys converted to strings and the first letter capitalized.

Returns:



168
169
170
# File 'lib/garcon/core_ext/hash.rb', line 168

def capitalize_keys
  transform_keys { |key| key.to_s.capitalize rescue key }
end

#compactHash

Returns a compacted copy (contains no key/value pairs having nil? values)

Examples:

hash = { a: 100, b: nil, c: false, d: '' }
hash.compact   # => { a: 100, c: false, d: '' }
hash           # => { a: 100, b: nil, c: false, d: '' }

Returns:



81
82
83
# File 'lib/garcon/core_ext/hash.rb', line 81

def compact
  select { |_, value| !value.nil? }
end

#except(*rejected) ⇒ Hash

Create a hash with all key/value pairs in receiver except rejected

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

Parameters:

Returns:

  • (Hash)

    A new hash without the selected keys.



217
218
219
220
221
# File 'lib/garcon/core_ext/hash.rb', line 217

def except(*rejected)
  hash = self.dup
  rejected.each {|k| hash.delete(k) }
  hash
end

#normalize_keysHash

Returns a new hash with all keys downcased and converted to symbols.

Returns:



118
119
120
# File 'lib/garcon/core_ext/hash.rb', line 118

def normalize_keys
  transform_keys { |key| key.downcase.to_sym rescue key }
end

#object_state(data = nil) ⇒ Object

Get or set state of object. You can think of #object_state as an in-code form of marshalling.



57
58
59
# File 'lib/garcon/core_ext/hash.rb', line 57

def object_state(data = nil)
  data ? replace(data) : dup
end

#only(*allowed) ⇒ Hash

Create a hash with only key/value pairs in receiver and allowed

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

Parameters:

Returns:

  • (Hash)

    A new hash with only the selected keys.



201
202
203
204
205
# File 'lib/garcon/core_ext/hash.rb', line 201

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

#recursive_fetch(*args, &block) ⇒ Hash, ...

Recursively searchs a nested datastructure for a key and returns the value. If a block is provided its value will be returned if the key does not exist

Examples:

options = { server: { location: { row: { rack: 34 } } } }
options.recursive_fetch :server, :location, :row, :rack
            # => 34
options.recursive_fetch(:non_existent_key) { 'default' }
            # => "default"

Returns:



237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/garcon/core_ext/hash.rb', line 237

def recursive_fetch(*args, &block)
  args.reduce(self) do |obj, arg|
    begin
      arg = Integer(arg) if obj.is_a? Array
      obj.fetch(arg)
    rescue ArgumentError, IndexError, NoMethodError => e
      break block.call(arg) if block
      raise UndefinedPathError,
        "Could not fetch path (#{args.join(' > ')}) at #{arg}", e.backtrace
    end
  end
end

#recursive_merge(other) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/garcon/core_ext/hash.rb', line 250

def recursive_merge(other)
  hash = self.dup
  other.each do |key, value|
    myval = self[key]
    if value.is_a?(Hash) && myval.is_a?(Hash)
      hash[key] = myval.recursive_merge(value)
    else
      hash[key] = value
    end
  end
  hash
end

#recursively_capitalize_keyHash

Returns a new Hash, recursively converting all keys to strings and the first letter capitalized.

Returns:



177
178
179
# File 'lib/garcon/core_ext/hash.rb', line 177

def recursively_capitalize_key
  recursively_transform_keys { |key| key.to_s.capitalize rescue key }
end

#recursively_normalize_keysHash

Returns a new Hash, recursively downcasing and converting all keys to symbols.

Returns:



127
128
129
# File 'lib/garcon/core_ext/hash.rb', line 127

def recursively_normalize_keys
  recursively_transform_keys { |key| key.downcase.to_sym rescue key }
end

#recursively_stringify_keyHash

Returns a new Hash, recursively converting all keys to strings.

Returns:



159
160
161
# File 'lib/garcon/core_ext/hash.rb', line 159

def recursively_stringify_key
  recursively_transform_keys { |key| key.to_s rescue key }
end

#recursively_symbolize_keysHash

Returns a new Hash, recursively converting all keys to symbols.

Returns:



143
144
145
# File 'lib/garcon/core_ext/hash.rb', line 143

def recursively_symbolize_keys
  recursively_transform_keys { |key| key.to_sym rescue key }
end

#recursively_transform_keys(&block) ⇒ Hash

Returns a new hash, recursively converting all keys by the block operation.

Returns:



109
110
111
# File 'lib/garcon/core_ext/hash.rb', line 109

def recursively_transform_keys(&block)
  _recursively_transform_keys_in_object(self, &block)
end

#stringify_keysHash

Returns a new hash with all keys converted to strings.

Returns:



151
152
153
# File 'lib/garcon/core_ext/hash.rb', line 151

def stringify_keys
  transform_keys { |key| key.to_s rescue key }
end

#symbolize_keysHash

Returns a new hash with all keys converted to symbols.

Returns:



135
136
137
# File 'lib/garcon/core_ext/hash.rb', line 135

def symbolize_keys
  transform_keys { |key| key.to_sym rescue key }
end

#to_struct(struct_name) ⇒ Object

A method to convert a Hash into a Struct.

h = { :name => "Earl", "age" => 20, "sex" => "lots", "worries" => "none" }
s = h.to_struct("Foo")


50
51
52
# File 'lib/garcon/core_ext/hash.rb', line 50

def to_struct(struct_name)
  Struct.new(struct_name,*keys).new(*values)
end

#transform_keysHash

Returns a new hash with all keys converted using the block operation.

Examples:

hash = { name: 'Tiggy', age: '15' }
hash.transform_keys{ |key| key.to_s.upcase }
  # => { "AGE" => "15", "NAME" => "Tiggy" }

Returns:



95
96
97
98
99
100
101
102
# File 'lib/garcon/core_ext/hash.rb', line 95

def transform_keys
  enum_for(:transform_keys) unless block_given?
  result = self.class.new
  each_key do |key|
    result[yield(key)] = self[key]
  end
  result
end

#zip(col1, col2) ⇒ Object

Creates a new hash from two separate arrays, a keys array and a values array.

Examples:

Hash.zip(['a','b','c'], [1,2,3])
# => { "a"=>1, "b"=>2, "c"=>3 }


188
189
190
# File 'lib/garcon/core_ext/hash.rb', line 188

def zip(col1, col2)
  col1.zip(col2).inject({}) { |r, i| r[i[0]] = i[1]; r }
end