Class: ResourceStruct::StrictStruct

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

Overview

StrictStruct provides a struct by which accessing undefined fields raises a MethodMissing error. This protects against accessing fields that are not present in API Responses.

If you need to check whether a field exists in an api response, you can via name? methods.

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

struct.foo? # => true struct.brr? # => false struct.foo # => 1 struct.bar # => [StrictStruct<{ “baz” => 2 }>, 3] struct.brr # => NoMethodError 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, &blk) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/resource_struct/strict_struct.rb', line 25

def method_missing(name, *args, &blk)
  args_length = args.length
  return self[name] if ___key?(name) && args_length.zero?
  return !!self[name[...-1]] if name.end_with?("?") && args_length.zero?

  super
end

Instance Method Details

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

Returns:

  • (Boolean)


33
34
35
# File 'lib/resource_struct/strict_struct.rb', line 33

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