Class: ResourceStruct::StrictStruct
- Inherits:
-
Object
- Object
- ResourceStruct::StrictStruct
- 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
- #method_missing(name, *args) ⇒ Object
- #respond_to_missing?(name, include_private = false) ⇒ Boolean
-
#to_h ⇒ Object
(also: #to_hash)
StrictStruct is documented as immutable.
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
32 33 34 35 36 37 38 |
# File 'lib/resource_struct/strict_struct.rb', line 32 def method_missing(name, *args, &) 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
40 41 42 |
# File 'lib/resource_struct/strict_struct.rb', line 40 def respond_to_missing?(name, include_private = false) ___key?(name) || ___key?(name.to_s.chomp("?")) || super end |
#to_h ⇒ Object Also known as: to_hash
StrictStruct is documented as immutable. Return a shallow copy so callers cannot mutate the internal canonicalized hash through #to_h / #to_hash.
27 28 29 |
# File 'lib/resource_struct/strict_struct.rb', line 27 def to_h @hash.dup end |