Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/helper_classes/hashaccessor.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(s, *args) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/helper_classes/hashaccessor.rb', line 22

def method_missing(s, *args)
  case s.to_s
    when "to_ary"
      super(s, args)
    when /^_.*[^=]$/
      key = s.to_s.sub(/^_{1,2}/, '').to_sym
      self.has_key? key and return self[key]
      self.has_key? key.to_s and return self[key.to_s]
      if s.to_s =~ /^__/
        return self[key] = {}
      else
        return nil
      end
    when /^_.*=$/
      key = /^_{1,2}(.*)=$/.match(s.to_s)[1].to_sym
      self.has_key? key and return self[key] = args[0]
      self.has_key? key.to_s and return self[key.to_s] = args[0]
      return self[key] = args[0]
    else
      super(s, args)
  end
end

Instance Method Details

#to_symObject

Converts all keys of a hash to syms recursively



10
11
12
13
14
15
16
# File 'lib/helper_classes/hashaccessor.rb', line 10

def to_sym
  ret = {}
  each { |k, v|
    ret[k.to_sym] = v.class == Hash ? v.to_sym : v
  }
  ret
end

#to_sym!Object



18
19
20
# File 'lib/helper_classes/hashaccessor.rb', line 18

def to_sym!
  self.replace(to_sym())
end