Module: Hash::EasyAccess

Included in:
LocalConf
Defined in:
lib/vex/base/hash/easy_access.rb

Defined Under Namespace

Modules: Etest

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/vex/base/hash/easy_access.rb', line 23

def method_missing(sym, *args, &block)
  return super if block_given?
  
  if args.length == 0 && sym.to_s =~ /^(.*)\?$/
    !! EasyAccess.check(self, $1)
  elsif args.length == 0
    EasyAccess.fetch(self, sym)
  elsif args.length == 1 && sym.to_s =~ /^(.*)\=$/
    v = args.first 
    v = v.dup if v.is_a?(Hash)
    EasyAccess.set(self, $1, v)
  else
    super
  end
end

Class Method Details

.check(hash, key) ⇒ Object


54
55
56
# File 'lib/vex/base/hash/easy_access.rb', line 54

def self.check(hash, key)
  check_key(hash, key.to_s) || check_key(hash, key.to_sym)
end

.check_key(hash, key) ⇒ Object


50
51
52
# File 'lib/vex/base/hash/easy_access.rb', line 50

def self.check_key(hash, key)
  key if hash.key?(key)
end

.easy_access(obj) ⇒ Object


71
72
73
74
# File 'lib/vex/base/hash/easy_access.rb', line 71

def self.easy_access(obj)
  obj.easy_access! if obj.is_a?(Hash)
  obj
end

.extended(host) ⇒ Object


19
20
21
# File 'lib/vex/base/hash/easy_access.rb', line 19

def self.extended(host)
  host.instance_variable_set "@easy_accessible", true
end

.fetch(hash, key) ⇒ Object


58
59
60
61
62
63
64
# File 'lib/vex/base/hash/easy_access.rb', line 58

def self.fetch(hash, key)
  if !(k = check(hash, key))
    raise NoMethodError, "undefined key `#{key}' for #{self.inspect}"
  end
  
  easy_access hash.fetch(k)
end

.set(hash, key, value) ⇒ Object


66
67
68
69
# File 'lib/vex/base/hash/easy_access.rb', line 66

def self.set(hash, key, value)
  k = check(hash, key) || key
  hash[k] = value
end

Instance Method Details

#respond_to?(sym) ⇒ Boolean

Returns:

  • (Boolean)

39
40
41
42
43
44
45
46
47
48
# File 'lib/vex/base/hash/easy_access.rb', line 39

def respond_to?(sym)
  key = case sym.to_s
  when /^(.*)[=\?]$/
    $1
  else
    sym.to_s
  end

  EasyAccess.check(self, key) || super
end