Module: Structure

Defined in:
lib/structure.rb,
lib/structure/rbs.rb,
lib/structure/types.rb,
lib/structure/builder.rb,
lib/structure/version.rb

Overview

A library for parsing data into immutable Ruby Data objects with type coercion

Defined Under Namespace

Modules: RBS, Types Classes: Builder

Constant Summary collapse

VERSION =
"4.1.0"

Class Method Summary collapse

Class Method Details

.new {|Builder| ... } ⇒ Class

Creates a new Data class with attribute definitions and type coercion

Examples:

Basic usage

Person = Structure.new do
  attribute :name, String
  attribute :age, Integer
end

person = Person.parse(name: "Alice", age: "30")
person.name # => "Alice"
person.age  # => 30

Yields:

  • (Builder)

    Block for defining attributes using the DSL

Returns:

  • (Class)

    A Data class with a parse method



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/structure.rb', line 22

def new(&block)
  builder = Builder.new
  builder.instance_eval(&block) if block

  # @type var klass: untyped
  klass = Data.define(*builder.attributes)

  # Enable custom method definitions by evaluating block on the class
  if block
    # Provide temporary dummy DSL methods to prevent NoMethodError during class_eval
    klass.define_singleton_method(:attribute) { |*args, **kwargs, &blk| }
    klass.define_singleton_method(:attribute?) { |*args, **kwargs, &blk| }
    klass.define_singleton_method(:after_parse) { |&blk| }

    # Evaluate block in class context for method definitions
    klass.class_eval(&block)

    # Remove temporary DSL methods
    klass.singleton_class.send(:remove_method, :attribute)
    klass.singleton_class.send(:remove_method, :attribute?)
    klass.singleton_class.send(:remove_method, :after_parse)
  end

  # Override initialize to make optional attributes truly optional
  optional_attrs = builder.optional
  unless optional_attrs.empty?
    klass.class_eval do
      alias_method(:__data_initialize__, :initialize)

      define_method(:initialize) do |**kwargs| # steep:ignore
        optional_attrs.each do |attr|
          kwargs[attr] = nil unless kwargs.key?(attr)
        end
        __data_initialize__(**kwargs) # steep:ignore
      end
    end
  end

  builder.predicate_methods.each do |pred, attr|
    klass.define_method(pred) { !!public_send(attr) }
  end

  # Store metadata on class to avoid closure capture (memory optimization)
  meta = {
    types: builder.types,
    defaults: builder.defaults,
    mappings: builder.mappings,
    coercions: builder.coercions(klass),
    after_parse: builder.after_parse_callback,
    required: builder.required,
  }.freeze
  klass.instance_variable_set(:@__structure_meta__, meta)
  klass.singleton_class.attr_reader(:__structure_meta__)

  # recursive to_h
  klass.define_method(:to_h) do
    klass.members.to_h do |m|
      v = public_send(m)
      value = case v
      when Array then v.map { |x| x.respond_to?(:to_h) && x ? x.to_h : x }
      when ->(x) { x.respond_to?(:to_h) && x } then v.to_h
      else v
      end
      [m, value]
    end
  end

  # parse accepts JSON-ish hashes + optional overrides hash
  # overrides is a positional arg (not **kwargs) to avoid hash allocation when unused
  #
  # @type self: singleton(Data) & _StructuredDataClass
  # @type var final: Hash[Symbol, untyped]
  klass.singleton_class.define_method(:parse) do |data = {}, overrides = nil|
    return data if data.is_a?(self)

    unless data.respond_to?(:merge!)
      raise TypeError, "can't convert #{data.class} into #{self}"
    end

    overrides&.each { |k, v| data[k.to_s] = v }

    final       = {}
    mappings    = __structure_meta__[:mappings]
    defaults    = __structure_meta__[:defaults]
    after_parse = __structure_meta__[:after_parse]
    required    = __structure_meta__[:required]

    # Check for missing required attributes
    required.each do |attr|
      from = mappings[attr]
      next if data.key?(from) || data.key?(from.to_sym) || defaults.key?(attr)

      raise ArgumentError, "missing keyword: :#{attr}"
    end

    mappings.each do |attr, from|
      value = data.fetch(from) do
        data.fetch(from.to_sym) do
          defaults[attr]
        end
      end

      if value
        coercion = __structure_meta__[:coercions][attr]
        value = coercion.call(value) if coercion
      end

      final[attr] = value
    end

    obj = new(**final)
    after_parse&.call(obj)
    obj
  end

  klass
end