Sha256: f1d84ea5e50fceca0e9935030800c7c679b5ebd062b6922185a12fe980b2aeac

Contents?: true

Size: 1.44 KB

Versions: 19

Compression:

Stored size: 1.44 KB

Contents

# frozen_string_literal: true

module ActiveElement
  # Generates a schema for a JSON form field based on values stored in the database.
  class JsonFieldSchema
    def initialize(table:, column:)
      @table = table
      @column = column
    end

    def schema
      data.map { |datum| structure(datum) }
    end

    private

    attr_reader :table, :column, :initial_structure

    def data
      @data ||= ActiveRecord::Base.connection
                                  .execute("select #{column} from #{table}")
                                  .pluck(column)
                                  .map { |datum| JSON.parse(datum) }
    end

    def structure(datum)
      {
        type: schema_type(datum),
        shape: schema_shape(datum)&.compact,
        fields: schema_fields(datum)&.compact
      }
    end

    def schema_type(val)
      case val
      when Hash
        'object'
      when Array
        'array'
      when String
        'string'
      end
    end

    def schema_shape(val)
      return nil unless %w[array object].include?(schema_type(val))
      return val.map { |item| structure(item).compact } if schema_type(val) == 'array'
      return val.map { |_key, value| structure(value).compact } if schema_type(val) == 'object'

      { type: schema_type(val) }
    end

    def schema_fields(val)
      return nil unless schema_type(val) == 'object'

      val.map { |key, value| { name: key }.merge(structure(value)).compact }
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
active_element-0.0.31 lib/active_element/json_field_schema.rb
active_element-0.0.30 lib/active_element/json_field_schema.rb
active_element-0.0.29 lib/active_element/json_field_schema.rb
active_element-0.0.28 lib/active_element/json_field_schema.rb
active_element-0.0.27 lib/active_element/json_field_schema.rb
active_element-0.0.26 lib/active_element/json_field_schema.rb
active_element-0.0.24 lib/active_element/json_field_schema.rb
active_element-0.0.23 lib/active_element/json_field_schema.rb
active_element-0.0.22 lib/active_element/json_field_schema.rb
active_element-0.0.21 lib/active_element/json_field_schema.rb
active_element-0.0.19 lib/active_element/json_field_schema.rb
active_element-0.0.18 lib/active_element/json_field_schema.rb
active_element-0.0.17 lib/active_element/json_field_schema.rb
active_element-0.0.16 lib/active_element/json_field_schema.rb
active_element-0.0.15 lib/active_element/json_field_schema.rb
active_element-0.0.14 lib/active_element/json_field_schema.rb
active_element-0.0.13 lib/active_element/json_field_schema.rb
active_element-0.0.12 lib/active_element/json_field_schema.rb
active_element-0.0.11 lib/active_element/json_field_schema.rb