Class: Synthra::ActiveRecordInference::SchemaBuilder
- Inherits:
-
Object
- Object
- Synthra::ActiveRecordInference::SchemaBuilder
- Defined in:
- lib/synthra/activerecord_inference.rb
Overview
Internal schema builder
Instance Method Summary collapse
- #add_field(name, type, **options) ⇒ Object
- #add_relationship(type, name, target) ⇒ Object
- #build ⇒ Object
- #has_field?(name) ⇒ Boolean
-
#initialize(name) ⇒ SchemaBuilder
constructor
A new instance of SchemaBuilder.
- #set_max_length(name, max) ⇒ Object
- #set_min_length(name, min) ⇒ Object
- #set_required(name) ⇒ Object
- #update_type(name, type) ⇒ Object
Constructor Details
#initialize(name) ⇒ SchemaBuilder
Returns a new instance of SchemaBuilder.
330 331 332 333 334 |
# File 'lib/synthra/activerecord_inference.rb', line 330 def initialize(name) @name = name @fields = {} @relationships = [] end |
Instance Method Details
#add_field(name, type, **options) ⇒ Object
336 337 338 339 340 341 |
# File 'lib/synthra/activerecord_inference.rb', line 336 def add_field(name, type, **) @fields[name] = { type: type, options: } end |
#add_relationship(type, name, target) ⇒ Object
374 375 376 |
# File 'lib/synthra/activerecord_inference.rb', line 374 def add_relationship(type, name, target) @relationships << { type: type, name: name, target: target } end |
#build ⇒ Object
378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'lib/synthra/activerecord_inference.rb', line 378 def build # Create DSL string dsl_lines = ["#{@name}:"] @fields.each do |name, config| optional = config[:options][:optional] ? "?" : "" dsl_lines << " #{name}#{optional}: #{config[:type]}" end dsl_string = dsl_lines.join("\n") # Parse and return schema Synthra::Parser.parse(dsl_string).first end |
#has_field?(name) ⇒ Boolean
343 344 345 |
# File 'lib/synthra/activerecord_inference.rb', line 343 def has_field?(name) @fields.key?(name) end |
#set_max_length(name, max) ⇒ Object
355 356 357 358 359 360 361 362 |
# File 'lib/synthra/activerecord_inference.rb', line 355 def set_max_length(name, max) return unless @fields[name] current_type = @fields[name][:type] if current_type == "text" @fields[name][:type] = "text(1..#{max})" end end |
#set_min_length(name, min) ⇒ Object
364 365 366 367 368 369 370 371 372 |
# File 'lib/synthra/activerecord_inference.rb', line 364 def set_min_length(name, min) return unless @fields[name] current_type = @fields[name][:type] if current_type.start_with?("text") max = current_type.match(/\.\.(\d+)/)&.[](1) || 255 @fields[name][:type] = "text(#{min}..#{max})" end end |
#set_required(name) ⇒ Object
351 352 353 |
# File 'lib/synthra/activerecord_inference.rb', line 351 def set_required(name) @fields[name][:options][:optional] = false if @fields[name] end |
#update_type(name, type) ⇒ Object
347 348 349 |
# File 'lib/synthra/activerecord_inference.rb', line 347 def update_type(name, type) @fields[name][:type] = type if @fields[name] end |