Class: HashObject

Inherits:
Object show all
Defined in:
lib/wdd-ruby-ext/utils/hash_object.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash_obj, no_exception_on_missing_key = false) ⇒ HashObject

Returns a new instance of HashObject.



2
3
4
5
# File 'lib/wdd-ruby-ext/utils/hash_object.rb', line 2

def initialize hash_obj, no_exception_on_missing_key = false
  @hash_obj = hash_obj
  @no_exception_on_missing_key = no_exception_on_missing_key
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/wdd-ruby-ext/utils/hash_object.rb', line 24

def method_missing method, *args
  key = method.to_s
  if @hash_obj.keys.include? key
    obj = @hash_obj[key]
    obj = HashObject.new(obj) if obj.is_a? Hash
    return obj
  elsif @hash_obj.keys.include? key.to_sym
    obj = @hash_obj[key.to_sym]
    obj = HashObject.new(obj) if obj.is_a? Hash
    return obj
  elsif matches = key.match( /(\w*)=/ )
    key = matches[1].to_sym
    @hash_obj[key]=args.first
  else
    raise "No field in Hash object: #{key}" unless @no_exception_on_missing_key
  end
end

Instance Method Details

#[](key) ⇒ Object



7
8
9
# File 'lib/wdd-ruby-ext/utils/hash_object.rb', line 7

def [] key
  @hash_obj[key]
end

#keysObject



11
12
13
# File 'lib/wdd-ruby-ext/utils/hash_object.rb', line 11

def keys
  return @hash_obj.keys
end

#merge(hash) ⇒ Object



15
16
17
# File 'lib/wdd-ruby-ext/utils/hash_object.rb', line 15

def merge hash
  HashObject.new(@hash_obj.merge( hash ))
end

#merge!(hash) ⇒ Object



19
20
21
22
# File 'lib/wdd-ruby-ext/utils/hash_object.rb', line 19

def merge! hash
  @hash_obj.merge!( hash )
  self
end