Sha256: b20e9baf2b3d903adb7bd3f9ea2951f4f35bb0e70ede8ed9a244a2dc75d84a23

Contents?: true

Size: 1.54 KB

Versions: 19

Compression:

Stored size: 1.54 KB

Contents

module FactoryBot
  # @api private
  class AttributeList
    include Enumerable

    def initialize(name = nil, attributes = [])
      @name = name
      @attributes = attributes
    end

    def define_attribute(attribute)
      ensure_attribute_not_self_referencing! attribute
      ensure_attribute_not_defined! attribute

      add_attribute attribute
    end

    def each(&block)
      @attributes.each(&block)
    end

    def names
      map(&:name)
    end

    def associations
      AttributeList.new(@name, select(&:association?))
    end

    def ignored
      AttributeList.new(@name, select(&:ignored))
    end

    def non_ignored
      AttributeList.new(@name, reject(&:ignored))
    end

    def apply_attributes(attributes_to_apply)
      attributes_to_apply.each { |attribute| add_attribute(attribute) }
    end

    private

    def add_attribute(attribute)
      @attributes << attribute
      attribute
    end

    def ensure_attribute_not_defined!(attribute)
      if attribute_defined?(attribute.name)
        raise AttributeDefinitionError, "Attribute already defined: #{attribute.name}"
      end
    end

    def ensure_attribute_not_self_referencing!(attribute)
      if attribute.respond_to?(:factory) && attribute.factory == @name
        message = "Self-referencing association '#{attribute.name}' in '#{attribute.factory}'"
        raise AssociationDefinitionError, message
      end
    end

    def attribute_defined?(attribute_name)
      @attributes.any? do |attribute|
        attribute.name == attribute_name
      end
    end
  end
end

Version data entries

19 entries across 18 versions & 3 rubygems

Version Path
factory_bot-6.5.1 lib/factory_bot/attribute_list.rb
trusty-cms-7.0.9.1 vendor/bundle/ruby/3.1.0/gems/factory_bot-6.5.0/lib/factory_bot/attribute_list.rb
trusty-cms-7.0.9.1 vendor/bundle/ruby/3.3.0/gems/factory_bot-6.5.0/lib/factory_bot/attribute_list.rb
factory_bot-6.5.0 lib/factory_bot/attribute_list.rb
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/factory_bot-6.4.6/lib/factory_bot/attribute_list.rb
factory_bot-6.4.6 lib/factory_bot/attribute_list.rb
factory_bot-6.4.5 lib/factory_bot/attribute_list.rb
factory_bot-6.4.4 lib/factory_bot/attribute_list.rb
factory_bot-6.4.3 lib/factory_bot/attribute_list.rb
factory_bot-6.4.2 lib/factory_bot/attribute_list.rb
factory_bot-6.4.1 lib/factory_bot/attribute_list.rb
factory_bot-6.4.0 lib/factory_bot/attribute_list.rb
factory_bot-6.3.0 lib/factory_bot/attribute_list.rb
factory_bot-6.2.1 lib/factory_bot/attribute_list.rb
factory_bot-6.2.0 lib/factory_bot/attribute_list.rb
factory_bot-6.1.0 lib/factory_bot/attribute_list.rb
factory_bot-6.0.2 lib/factory_bot/attribute_list.rb
factory_bot-6.0.1 lib/factory_bot/attribute_list.rb
factory_bot-6.0.0 lib/factory_bot/attribute_list.rb