Class: HashWithIndifferentAccess

Inherits:
Object
  • Object
show all
Defined in:
lib/common/hash_with_indifferent_access.rb

Instance Method Summary collapse

Constructor Details

#initialize(data = nil) ⇒ HashWithIndifferentAccess

Returns a new instance of HashWithIndifferentAccess.



2
3
4
5
# File 'lib/common/hash_with_indifferent_access.rb', line 2

def initialize data=nil
  @data = {}
  merge! data if data
end

Instance Method Details

#[](key) ⇒ Object



18
19
20
# File 'lib/common/hash_with_indifferent_access.rb', line 18

def [] key
  @data[convert_key(key)]
end

#[]=(key, value) ⇒ Object Also known as: store



22
23
24
# File 'lib/common/hash_with_indifferent_access.rb', line 22

def []= key, value
  @data[convert_key(key)] = convert_value(value)
end

#clearObject



56
57
58
# File 'lib/common/hash_with_indifferent_access.rb', line 56

def clear
  @data.keys.each { |key| @data.delete(key) }
end

#delete(key) ⇒ Object



42
43
44
# File 'lib/common/hash_with_indifferent_access.rb', line 42

def delete key
  @data.delete convert_key(key)
end

#delete_if(&block) ⇒ Object



38
39
40
# File 'lib/common/hash_with_indifferent_access.rb', line 38

def delete_if &block
  @data.delete_if(&block)
end

#dig(*args) ⇒ Object



46
47
48
49
# File 'lib/common/hash_with_indifferent_access.rb', line 46

def dig *args
  list = args.map{ |it| it.is_a?(Symbol) ? it.to_s : it }
  @data.dig *list
end

#eachObject



60
# File 'lib/common/hash_with_indifferent_access.rb', line 60

def each;    @data.each { |k,v| yield(k,v) }; end

#key?(name) ⇒ Boolean Also known as: include?, has_key?, member?

Returns:

  • (Boolean)


27
28
29
# File 'lib/common/hash_with_indifferent_access.rb', line 27

def key? name
  @data.key? convert_key(name)
end

#keysObject



61
# File 'lib/common/hash_with_indifferent_access.rb', line 61

def keys;    @data.keys; end

#merge(data) ⇒ Object



12
13
14
15
16
# File 'lib/common/hash_with_indifferent_access.rb', line 12

def merge data
  copy = self.class.new @data
  copy.merge! data
  copy
end

#merge!(data) ⇒ Object Also known as: update



7
8
9
# File 'lib/common/hash_with_indifferent_access.rb', line 7

def merge! data
  data.each { |key, value| @data[convert_key(key)] = convert_value(value) }
end

#pluck(*args) ⇒ Object



51
52
53
54
# File 'lib/common/hash_with_indifferent_access.rb', line 51

def pluck *args
  args = args.map(&:to_s)
  @data.select { |k,v| args.include?(k) }
end

#to_hashObject



63
# File 'lib/common/hash_with_indifferent_access.rb', line 63

def to_hash; @data; end

#to_json(opts = nil) ⇒ Object



34
35
36
# File 'lib/common/hash_with_indifferent_access.rb', line 34

def to_json opts=nil
  @data.to_json opts
end

#valuesObject



62
# File 'lib/common/hash_with_indifferent_access.rb', line 62

def values;  @data.keys; end