Class: SafeHash

Inherits:
BasicObject
Defined in:
lib/crystal/support/safe_hash.rb

Direct Known Subclasses

Crystal::Config

Defined Under Namespace

Classes: SafeNil

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ SafeHash

Returns a new instance of SafeHash.



6
7
8
# File 'lib/crystal/support/safe_hash.rb', line 6

def initialize hash = {}
  reinitialize hash
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/crystal/support/safe_hash.rb', line 51

def method_missing m, *args
  m = m.to_s
  if m.last == '='
    self[m[0..-2]] = *args
  else
    self[m, *args]
  end
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



4
5
6
# File 'lib/crystal/support/safe_hash.rb', line 4

def hash
  @hash
end

Instance Method Details

#[](key, *args) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/crystal/support/safe_hash.rb', line 19

def [] key, *args     
  key = key.to_s
  if key.last == '!'
    key = key[0..-2]
    if @hash.include? key
      @hash[key]
    else
      raise "No key #{key}"
    end
  elsif key.last == '?'
    key = key[0..-2]
    @hash.include? key
  else
    if @hash.include? key
      @hash[key]
    elsif args.empty?
      SafeNil.instance
    else
      return *args
    end
  end
end

#[]=(key, value) ⇒ Object



10
11
12
13
# File 'lib/crystal/support/safe_hash.rb', line 10

def []= key, value
  value = SafeHash.new value if value.is_a? Hash
  @hash[key.to_s] = value
end

#delete(key) ⇒ Object



68
69
70
# File 'lib/crystal/support/safe_hash.rb', line 68

def delete key
  @hash.delete key.to_s
end

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/crystal/support/safe_hash.rb', line 15

def include? key
  @hash.include? key.to_s
end

#inspectObject



64
65
66
# File 'lib/crystal/support/safe_hash.rb', line 64

def inspect
  @hash.inspect
end

#is_a_safe_hash?Boolean

Returns:

  • (Boolean)


86
87
88
# File 'lib/crystal/support/safe_hash.rb', line 86

def is_a_safe_hash?
  true
end

#reinitialize(hash) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/crystal/support/safe_hash.rb', line 42

def reinitialize hash
  @hash = {}
  hash.each do |k, v|
    v = SafeHash.new v if v.is_a? Hash 
    @hash[k.to_s] = v
  end
  # @hash.freeze
end

#to_hashObject Also known as: to_h

deep conversion, check and converts nested SafeHashes to Hashes



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/crystal/support/safe_hash.rb', line 73

def to_hash    
  r = {}
  @hash.each do |k, v|
    r[k] = if v.respond_to :is_a_safe_hash?
      v.to_hash
    else
      v
    end
  end
  r
end

#to_yaml(*args) ⇒ Object



60
61
62
# File 'lib/crystal/support/safe_hash.rb', line 60

def to_yaml *args
  @hash.to_yaml *args
end