Sha256: 878740d890874ecf5fc4aa8a1f24a2b51291d14e37e468fea3732f61fbe87022

Contents?: true

Size: 1.85 KB

Versions: 6

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true

require 'rspec/rails/api/field_config'

module RSpec
  module Rails
    module Api
      # Represents an entity configuration.
      # Basically, entities configuration only have a collection of fields
      # and a method to serialize them for comparison with actual content
      class EntityConfig
        attr_accessor :fields

        def initialize(fields)
          @fields = {}
          fields.each_pair do |name, definition|
            @fields[name] = FieldConfig.new(**definition)
          end
        end

        ##
        # @return [Hash] Entity configuration
        def to_h
          out = {}
          @fields.each_key do |key|
            out[key] = @fields[key].to_h
          end
          out
        end

        ##
        # Replaces the arrays 'of' and objects 'attributes' with the corresponding
        # entities, recursively
        #
        # @param entities [Hash] List of entities
        #
        # @return [Hash]
        def expand_with(entities)
          hash = to_h
          hash.each_pair do |field, config|
            next unless %i[array object].include? config[:type]

            attribute = config[:attributes]
            next unless attribute.is_a? Symbol

            hash[field][:attributes] = expand_attribute attribute, entities
          end
        end

        private

        ##
        # Expands an attribute for "for" and "attributes" keys
        #
        # @param attribute [Symbol] Attribute name
        # @param entities  [Hash]   List of entities
        def expand_attribute(attribute, entities)
          # Primitives support
          return { type: attribute } if PRIMITIVES.include? attribute

          raise "Entity #{attribute} not found for entity completion." unless entities[attribute]

          entities[attribute].expand_with(entities)
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rspec-rails-api-0.8.0 lib/rspec/rails/api/entity_config.rb
rspec-rails-api-0.7.0 lib/rspec/rails/api/entity_config.rb
rspec-rails-api-0.6.3 lib/rspec/rails/api/entity_config.rb
rspec-rails-api-0.6.2 lib/rspec/rails/api/entity_config.rb
rspec-rails-api-0.6.1 lib/rspec/rails/api/entity_config.rb
rspec-rails-api-0.6.0 lib/rspec/rails/api/entity_config.rb