Class: Nocode::Util::Dictionary

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/nocode/util/dictionary.rb

Overview

A hash-like object which ensures all keys are strings.

Constant Summary collapse

NEWLINE_CHAR =
"\n"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values = {}) ⇒ Dictionary

Returns a new instance of Dictionary.



25
26
27
28
29
30
31
# File 'lib/nocode/util/dictionary.rb', line 25

def initialize(values = {})
  @values = {}

  (values || {}).each { |k, v| assign(k, v) }

  freeze
end

Instance Attribute Details

#valuesObject (readonly)

Returns the value of attribute values.



21
22
23
# File 'lib/nocode/util/dictionary.rb', line 21

def values
  @values
end

Class Method Details

.ensure(value) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/nocode/util/dictionary.rb', line 12

def ensure(value)
  if value.is_a?(self)
    value
  else
    new(value)
  end
end

Instance Method Details

#[](key) ⇒ Object



41
42
43
# File 'lib/nocode/util/dictionary.rb', line 41

def [](key)
  values[keyify(key)]
end

#[]=(key, value) ⇒ Object



37
38
39
# File 'lib/nocode/util/dictionary.rb', line 37

def []=(key, value)
  tap { values[keyify(key)] = value }
end

#delete(key) ⇒ Object



33
34
35
# File 'lib/nocode/util/dictionary.rb', line 33

def delete(key)
  tap { values.delete(keyify(key)) }
end

#dig(*keys) ⇒ Object



45
46
47
48
49
50
# File 'lib/nocode/util/dictionary.rb', line 45

def dig(*keys)
  top_level = keyify(keys.first)
  keys = [top_level] + keys[1..]

  values.dig(*keys)
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/nocode/util/dictionary.rb', line 52

def key?(key)
  values.key?(keyify(key))
end

#to_sObject



56
57
58
# File 'lib/nocode/util/dictionary.rb', line 56

def to_s
  values.map { |k, v| "#{k}: #{v}" }.join(NEWLINE_CHAR)
end