# frozen_string_literal: true require 'rspec/rails/api/entity_config' require 'rspec/rails/api/validator' module RSpec module Rails module Api # Represents an entity field configuration. # A field have some options and a method to serialize itself. class FieldConfig attr_accessor :required, :type, :attributes, :description def initialize(type:, description:, required: true, attributes: nil, of: nil) # rubocop:disable Metrics/CyclomaticComplexity @required = required @description = description raise "Field type not allowed: '#{type}'" unless Validator.valid_type?(type) raise "Don't use 'of' on non-arrays" if of && type != :array raise "Don't use 'attributes' on non-objects" if attributes && type != :object define_attributes attributes if type == :object define_attributes of if type == :array @type = type end ## # @return [Hash] Field configuration def to_h out = { required: @required, type: @type } out[:description] = @description unless @description.nil? if %i[object array].include?(@type) && @attributes out[:attributes] = if @attributes.is_a? EntityConfig @attributes.to_h elsif attributes.is_a? Symbol @attributes end end out end private ## # Sets @attributes of the field when it's an Array or Hash # # @param attributes [Hash, Symbol] The attributes definition or reference # # @return [void] def define_attributes(attributes) @attributes = case attributes when Hash EntityConfig.new attributes when Symbol attributes end end end end end end