Class: Lluminary::SchemaModel

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/lluminary/schema_model.rb

Overview

Base class for models that use JSON schema validation. Provides ActiveModel integration and schema validation.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ SchemaModel

Returns a new instance of SchemaModel.



13
14
15
# File 'lib/lluminary/schema_model.rb', line 13

def initialize(attributes = {})
  @attributes = attributes.transform_keys(&:to_s)
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



10
11
12
# File 'lib/lluminary/schema_model.rb', line 10

def attributes
  @attributes
end

#task_instanceObject

Returns the value of attribute task_instance.



11
12
13
# File 'lib/lluminary/schema_model.rb', line 11

def task_instance
  @task_instance
end

Class Method Details

.build(fields:, validations:, custom_validations: []) ⇒ Object



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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/lluminary/schema_model.rb', line 23

def self.build(fields:, validations:, custom_validations: [])
  Class.new(self) do
    class << self
      attr_accessor :schema_fields, :custom_validation_methods
    end

    self.schema_fields = fields
    self.custom_validation_methods = custom_validations

    # Add accessors for each field
    fields.each_key do |name|
      define_method(name) { @attributes[name.to_s] }
      define_method("#{name}=") { |value| @attributes[name.to_s] = value }
    end

    # Add raw_response field and validation
    define_method(:raw_response) { @attributes["raw_response"] }
    define_method("raw_response=") do |value|
      @attributes["raw_response"] = value
    end

    # Add custom validation hook
    validate do |record|
      # Run custom validations from the task if present
      if record.task_instance &&
           !record.class.custom_validation_methods.empty?
        record.class.custom_validation_methods.each do |validation|
          method_name = validation[:method]
          if record.task_instance.respond_to?(method_name)
            record.task_instance.send(method_name)
          end
        end
      end

      if record.raw_response
        begin
          JSON.parse(record.raw_response)
        rescue JSON::ParserError
          record.errors.add(:raw_response, "must be valid JSON")
        end
      end

      record.attributes.each do |name, value|
        next if name == "raw_response"
        next if value.nil?

        field = self.class.schema_fields[name.to_sym]
        next unless field

        case field[:type]
        when :hash
          validate_hash_field(record, name, value, field)
        when :array
          validate_array_field(record, name, value, field[:element_type])
        when :dictionary
          validate_dictionary_field(record, name, value, field[:value_type])
        when :string
          unless value.is_a?(String)
            record.errors.add(name.to_s.capitalize, "must be a String")
          end
        when :integer
          unless value.is_a?(Integer)
            record.errors.add(name.to_s.capitalize, "must be an Integer")
          end
        when :boolean
          unless [true, false].include?(value)
            record.errors.add(name.to_s.capitalize, "must be true or false")
          end
        when :float
          unless value.is_a?(Float)
            record.errors.add(name.to_s.capitalize, "must be a float")
          end
        when :datetime
          unless value.is_a?(DateTime)
            record.errors.add(name.to_s.capitalize, "must be a DateTime")
          end
        end
      end
    end

    # Add ActiveModel validations
    validations.each { |args, options| validates(*args, **options) }

    # Set model name for error messages
    define_singleton_method(:model_name) do
      ActiveModel::Name.new(self, nil, "SchemaModel")
    end

    private

    def validate_dictionary_field(
      record,
      name,
      value,
      value_type,
      path = nil
    )
      field_name = path || name

      unless value.is_a?(Hash)
        record.errors.add(field_name, "must be a Hash")
        return
      end

      value.each do |key, val|
        current_path = "#{field_name}[#{key}]"

        case value_type[:type]
        when :string
          unless val.is_a?(String)
            record.errors.add(current_path, "must be a String")
          end
        when :integer
          unless val.is_a?(Integer)
            record.errors.add(current_path, "must be an Integer")
          end
        when :boolean
          unless [true, false].include?(val)
            record.errors.add(current_path, "must be true or false")
          end
        when :float
          unless val.is_a?(Float)
            record.errors.add(current_path, "must be a float")
          end
        when :datetime
          unless val.is_a?(DateTime)
            record.errors.add(current_path, "must be a DateTime")
          end
        when :hash
          validate_hash_field(
            record,
            current_path,
            val,
            value_type,
            current_path
          )
        when :array
          validate_array_field(
            record,
            current_path,
            val,
            value_type[:element_type],
            current_path
          )
        when :dictionary
          validate_dictionary_field(
            record,
            current_path,
            val,
            value_type[:value_type],
            current_path
          )
        end
      end
    end

    def validate_hash_field(
      record,
      name,
      value,
      field_definition,
      path = nil
    )
      field_name = path || name

      unless value.is_a?(Hash)
        record.errors.add(field_name, "must be a Hash")
        return
      end

      field_definition[:fields].each do |key, field|
        current_path = path ? "#{path}[#{key}]" : "#{field_name}[#{key}]"
        # Try both string and symbol keys
        field_value = value[key.to_s] || value[key.to_sym]

        next if field_value.nil?

        case field[:type]
        when :hash
          validate_hash_field(record, key, field_value, field, current_path)
        when :array
          validate_array_field(
            record,
            key,
            field_value,
            field[:element_type],
            current_path
          )
        when :dictionary
          validate_dictionary_field(
            record,
            key,
            field_value,
            field[:value_type],
            current_path
          )
        when :string
          unless field_value.is_a?(String)
            record.errors.add(current_path, "must be a String")
          end
        when :integer
          unless field_value.is_a?(Integer)
            record.errors.add(current_path, "must be an Integer")
          end
        when :boolean
          unless [true, false].include?(field_value)
            record.errors.add(current_path, "must be true or false")
          end
        when :float
          unless field_value.is_a?(Float)
            record.errors.add(current_path, "must be a float")
          end
        when :datetime
          unless field_value.is_a?(DateTime)
            record.errors.add(current_path, "must be a DateTime")
          end
        end
      end
    end

    def validate_array_field(record, name, value, element_type, path = nil)
      field_name = path || name

      unless value.is_a?(Array)
        record.errors.add(field_name, "must be an Array")
        return
      end

      return unless element_type # untyped array

      value.each_with_index do |element, index|
        current_path = "#{field_name}[#{index}]"

        case element_type[:type]
        when :hash
          validate_hash_field(
            record,
            name,
            element,
            element_type,
            current_path
          )
        when :array
          validate_array_field(
            record,
            name,
            element,
            element_type[:element_type],
            current_path
          )
        when :dictionary
          validate_dictionary_field(
            record,
            name,
            element,
            element_type[:value_type],
            current_path
          )
        when :string
          unless element.is_a?(String)
            record.errors.add(current_path, "must be a String")
          end
        when :integer
          unless element.is_a?(Integer)
            record.errors.add(current_path, "must be an Integer")
          end
        when :boolean
          unless [true, false].include?(element)
            record.errors.add(current_path, "must be true or false")
          end
        when :float
          unless element.is_a?(Float)
            record.errors.add(current_path, "must be a float")
          end
        when :datetime
          unless element.is_a?(DateTime)
            record.errors.add(current_path, "must be a DateTime")
          end
        end
      end
    end
  end
end

Instance Method Details

#to_sObject



17
18
19
20
21
# File 'lib/lluminary/schema_model.rb', line 17

def to_s
  attrs = attributes.dup
  attrs.delete("raw_response")
  "#<#{self.class.name} #{attrs.inspect}>"
end