Method: MediaTypes::Scheme#collection

Defined in:
lib/media_types/scheme.rb

#collection(key, scheme = nil, allow_empty: false, expected_type: ::Array, optional: false, &block) ⇒ Object

Expect a collection such as an array or hash.

The +block+ defines the Schema for each item in that collection.

Examples:

Collection with an array of string


class MyMedia
  include MediaTypes::Dsl

  validations do
    collection :foo, String
  end
end

MyMedia.valid?({ collection: ['foo', 'bar'] })
# => true

Collection with defined scheme


class MyMedia
  include MediaTypes::Dsl

  validations do
    collection :foo do
      attribute :required, String
      attribute :number, Numeric
    end
  end
end

MyMedia.valid?({ foo: [{ required: 'test', number: 42 }, { required: 'other', number: 0 }] })
# => true

Parameters:

  • key (Symbol)

    key of the collection (same as #attribute)

  • scheme (NilClass, Scheme, Class) (defaults to: nil)

    scheme to use if no &block is given, or type of each item in collection

  • allow_empty (TrueClass, FalseClass) (defaults to: false)

    if true accepts 0 items in an enumerable

  • expected_type (Class) (defaults to: ::Array)

    forces the value of this collection to be this type, defaults to Array.

Raises:

See Also:



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/media_types/scheme.rb', line 350

def collection(key, scheme = nil, allow_empty: false, expected_type: ::Array, optional: false, &block)
  raise ConflictingTypeDefinitionError, 'You cannot apply a block to a non-hash typed collection, either remove the type or the block' if scheme != ::Hash && block_given? && !scheme.nil?

  unless block_given?
    return rules.add(
      key,
      EnumerationOfType.new(
        scheme,
        enumeration_type: expected_type,
        allow_empty: allow_empty
      ),
      optional: optional
    )
  end

  rules.add(key, Scheme.new(allow_empty: allow_empty, expected_type: expected_type, &block), optional: optional)
end