Class: ResourceStruct::FlexStruct

Inherits:
Object
  • Object
show all
Includes:
Extensions::IndifferentLookup
Defined in:
lib/resource_struct/flex_struct.rb

Overview

FlexStruct provides a struct by which accessing undefined fields returns nil

struct = FlexStruct.new({ “foo” => 1, “bar” => [{ “baz” => 2 }, 3] })

struct.foo? # => true struct.brr? # => false struct.foo # => 1 struct.bar # => [FlexStruct<{ “baz” => 2 }>, 3] struct.brr # => nil struct # => 1 struct # => nil struct[:bar, 0, :baz] # => 2 struct[:bar, 0, :brr] # => nil

Instance Method Summary collapse

Methods included from Extensions::IndifferentLookup

#==, #dig, #initialize, #inspect, #marshal_dump, #marshal_load

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/resource_struct/flex_struct.rb', line 39

def method_missing(name, *args)
  if name.end_with?("=")
    return self[name[...-1]] = args.first if args.length == 1

    raise ArgumentError, "expected 1 argument received #{args.length} arguments"
  elsif name.end_with?("?")
    return !!self[name[...-1]] if args.empty?
  elsif args.empty?
    return self[name]
  end

  raise ArgumentError, "expected 0 arguments received #{args.length} arguments"
end

Instance Method Details

#[]=(key, value) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/resource_struct/flex_struct.rb', line 22

def []=(key, value)
  ckey = ___convert_key(key)
  @ro_struct.delete(ckey)

  value = value.instance_variable_get(:@hash) if value.is_a?(FlexStruct) || value.is_a?(StrictStruct)

  if @hash.key?(key)
    @hash[key] = value
  elsif key.is_a?(String) && @hash.key?(key.to_sym)
    @hash[key.to_sym] = value
  elsif key.is_a?(Symbol) && @hash.key?(key.to_s)
    @hash[key.to_s] = value
  else
    @hash[key] = value
  end
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


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

def respond_to_missing?(name, include_private = false)
  ___key?(name) || ___key?(name.to_s.chomp("?")) || super
end