Introspection reference
FieldStruct::Introspection walks a struct’s fields without changing anything, for code that exports a struct to another format. The JSON Schema, Avro and Protobuf adapters sit on top of it, and any adapter you write can too. It ships inside field_struct and loads with require 'field_struct'.
The walk reports declarations and nothing else. The adapter decides what null means for an optional field, which defaults to write, how types map and what a registered option does.
class Waypoint < FieldStruct::Base optional :label, :stringend
class Route < FieldStruct::Base required :name, :string optional :waypoints, :array, of: Waypoint serialize :json, waypoints: 'stops'end
name, stops = FieldStruct::Introspection.properties(Route)name.key # => "name"name.field.required? # => truestops.key # => "stops"stops.node.element.klass == Waypoint # => trueproperties
Section titled “properties”Introspection.properties(klass, serialization: :json) # => Array<Property>You get one Property for each field of klass, in declaration order and with inherited fields included. A struct without fields gives []. serialization is a Symbol or String that selects which serialize mapping names the keys, and a format nobody declared keeps every field name.
Every call returns a fresh array of fresh objects, and nothing is cached on the class.
FieldStruct::Introspection.properties(Route).map(&:key) # => ["name", "stops"]FieldStruct::Introspection.properties(Route, serialization: :csv).map(&:key) # => ["name", "waypoints"]FieldStruct::Introspection.properties(Class.new(FieldStruct::Base)) # => []FieldStruct::Introspection.properties(Route).first.equal?(FieldStruct::Introspection.properties(Route).first) # => falseProperty
Section titled “Property”| Reader | Returns |
|---|---|
field |
the class’s own FieldStruct::Field, not a copy |
key |
the external name for the chosen format, always a String |
node |
the node for the field’s type, built by Introspection.node(field.type_instance, field.options) |
Field has public readers an adapter may rely on: name (a Symbol), type (the resolved type class), type_instance (one per field), required?, sensitive?, description, default, options, coercion_policy and rbs_type.
Field#default is the raw declared default: a value or a callable, never called by the reader. nil means no default. A default of false, 0, '' or [] is a real default.
Node kinds
Section titled “Node kinds”node(type, options = {}) picks a node class from the type instance. There are exactly five, with no shared base class, so dispatch with case.
| Node | Built for | Readers |
|---|---|---|
ScalarNode |
every other type: :string, :integer, :value, custom types and the rest |
type, options |
ArrayNode |
Types::Array |
type, options, element |
MapNode |
Types::Hash |
type, options, element (the value node; keys are always Strings) |
UnionNode |
Types::Union |
type, members |
StructNode |
Types::Nested |
type, klass |
class Leg < FieldStruct::Base required :nights, :integer, in: 1..5 optional :tags, :array, of: :string, element: { strict: true } optional :ref, :union, of: %i[integer string] optional :stop, Waypointend
nights, tags, ref, stop = FieldStruct::Introspection.properties(Leg).map(&:node)
[nights, tags, ref, stop].map { |node| node.class.name.split('::').last }# => ["ScalarNode", "ArrayNode", "UnionNode", "StructNode"]nights.options # => {in: 1..5}tags.element.options # => {strict: true}ref.members.map { |member| member.type.ruby_type } # => [Integer, String]stop.klass # => WaypointScalar nodes
Section titled “Scalar nodes”type is the field’s own type instance. options is the Hash the value is checked against, which for a field is Field#options itself.
Array nodes
Section titled “Array nodes”options is whatever the array was declared with, so it holds of_type: and, when given, element:. It is {} if the array is an element of another array or a member of a union.
element is built on first read and the same value comes back afterwards, so an adapter that overrides the array at field level never pays for the element. It is:
- a
ScalarNodeforof: :string, built with theelement:options, or{} - a
StructNodeforof: Waypoint nilwhen the element type is unknown or is a union. An array of unions records only the union class, so its members can’t be reached from the array node- for
of: :array, anArrayNodewhose ownelementisnil, so an array of arrays has exactly two levels
class Timetable < FieldStruct::Base optional :days, :array, of: :array optional :slots, :array, of: :unionend
days, slots = FieldStruct::Introspection.properties(Timetable).map(&:node)days.element.class.name.split('::').last # => "ArrayNode"days.element.element # => nilslots.element # => nilUnion nodes
Section titled “Union nodes”members is a frozen Array holding one node per member in declared order. A member carries no options, so each node is built with an empty Hash.
Struct nodes
Section titled “Struct nodes”klass is a reference and is never expanded, so the walk doesn’t recurse into a struct’s own properties. Call properties(node.klass) yourself, and use named? plus a definitions table to cut off self-referential structs. The walk itself can’t loop.
Introspection.node(type, options = {}) # => ScalarNode | ArrayNode | MapNode | UnionNode | StructNodenode builds a node for a type instance and the options Hash it is checked with. Anything that isn’t an array, map, union or nested type becomes a ScalarNode, a non-type passed by mistake included.
count = FieldStruct::Introspection.node(FieldStruct::Types::Integer.new, in: 1..3)count.class.name.split('::').last # => "ScalarNode"count.options # => {in: 1..3}named?
Section titled “named?”Introspection.named?(klass) # => BooleanTrue when the class has a name usable as a definition key or title. An anonymous class gives false, and so does a class under an anonymous module, whose name looks like #<Module:0x...>::Addr. A class in an ordinary namespace gives true.
module Alpine class Refuge < FieldStruct::Base; endend
FieldStruct::Introspection.named?(Alpine::Refuge) # => trueFieldStruct::Introspection.named?(Class.new(FieldStruct::Base)) # => falseWhat options holds
Section titled “What options holds”Adapters read Field#options through the nodes, and these are the promises:
enum:andin:are as declared: an Array of Strings or Symbols, a Range or an Array.round:,base:andstrict:are as declared, andround:andvalues:are present only when declared.format:on a string-family field is a Regexp, the declared one or the type’s default.format:on a date or time field is the declared value:nilwhen none was given (the key is present), a preset Symbol such as:iso8601, or a String. It is never a resolved object.zone:is as written.values:on:booleanis the resolved Hash{truthy: [...], falsy: [...]}.- Registered options such as
avro:,proto:andjson_schema:are present verbatim. Core checks only the value’s class. - An element’s options are validated like a scalar field’s, so a registered option on an
element:raises at declaration. Registered options are for whole fields only.
FieldStruct.register_option(:unit, type: String, owner: 'climb_log')
class Climb < FieldStruct::Base required :gain, :float, round: 1, in: 0.0..99.9, unit: 'km' optional :logged, :dateend
gain, logged = FieldStruct::Introspection.properties(Climb).map(&:node)gain.options # => {round: 1, in: 0.0..99.9, unit: "km"}logged.options # => {format: nil}Stability promises
Section titled “Stability promises”- Every
Propertyand every node is frozen. TheoptionsHashes belong to the struct and are frozen shallowly at most, so treat what they hold (anenum:Array, avalues:Hash) as read-only. Introspectionmutates nothing and caches nothing on the class, and calling it never changes how a struct behaves. A field redeclared after a call is a newFieldthat the next call picks up.Metadata#serialization(format)returns the same frozen Hash until the class redeclares that format, andMetadata#eachyields the sameFieldobjects while a field stays unchanged. A cache keyed on those objects holds exactly until the class’s declarations change.- Core ships no exporter: there is no
FieldStruct::JSONSchema, noto_json_schema, and no format named other than:json.
Type readers
Section titled “Type readers”An adapter that maps types reads them off type_instance.
ruby_typeisIntegerfor:integer,Float,Stringfor the whole string family,[TrueClass, FalseClass]for:boolean,Symbol,Date,Time,DateTime,BigDecimal,Objectfor:value,Array,Hashfor:hash, the struct class for a nested field, and the flat list of member classes for a union.default_formatexists on:uuid,:url,:email(a Regexp) and on the date and time types (nil).default_roundexists on:floatand:big_decimal. Ask withrespond_to?first, since other types don’t define them.Types::Union#member_typesgives the member type instances, andTypes::Nested#struct_classgives the class.- An optional hook on a custom type, like
json_schema, is the adapter’s convention and not core’s. Checkrespond_to?on the instance and never assume the hook exists.
See also
Section titled “See also”FieldStruct, Actionable and their adapters are open source under the MIT license.