Class: DeepStruct::HashWrapper

Inherits:
DeepWrapper show all
Defined in:
lib/deepstruct.rb

Instance Method Summary collapse

Methods inherited from DeepWrapper

#initialize, #inspect, #to_json, #unwrap

Constructor Details

This class inherits a constructor from DeepStruct::DeepWrapper

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/deepstruct.rb', line 57

def method_missing(method, *args, &block)
  return @value.send(method, *args, &block) if @value.respond_to?(method)
  method = method.to_s
  if method.chomp!('?')
    key = method.to_sym
    self.has_key?(key) && !!self[key]
  elsif method.chomp!('=')
    raise ArgumentError, "wrong number of arguments (#{arg_count} for 1)", caller(1) if args.length != 1
    self[method] = args[0]
  elsif args.length == 0 && self.has_key?(method)
    self[method]
  else
    raise NoMethodError, "undefined method `#{method}' for #{self}", caller(1)
  end
end

Instance Method Details

#[](key) ⇒ Object



49
50
51
# File 'lib/deepstruct.rb', line 49

def [](key)
  indiffrently(key) { |key| DeepStruct.wrap(@value[key]) }
end

#[]=(key, value) ⇒ Object



45
46
47
# File 'lib/deepstruct.rb', line 45

def []=(key, value)
  indiffrently(key) { |key| @value[key] = value }
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/deepstruct.rb', line 53

def has_key?(key)
  indiffrently(key) { |key| @value.has_key?(key) }
end

#indiffrently(key, &block) ⇒ Object

Given a symbol or a string this yields the variant of the key that exists in the wrapped hash if any. If none exists (or the key is not a symbol or string) the input value is passed through unscathed.



38
39
40
41
42
43
# File 'lib/deepstruct.rb', line 38

def indiffrently(key, &block)
  return yield(key) if @value.has_key?(key)
  return yield(key.to_s) if key.is_a?(Symbol) && @value.has_key?(key.to_s)
  return yield(key.to_sym) if key.is_a?(String) && @value.has_key?(key.to_sym)
  return yield(key)
end

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/deepstruct.rb', line 31

def respond_to?(method, include_private = false)
  @value.respond_to?(method, include_private) || self.has_key?(method.to_s.chomp('='))
end