Method: MediaTypes::Scheme#attribute

Defined in:
lib/media_types/scheme.rb

#attribute(key, type = nil, optional: false, **opts, &block) ⇒ Object

Adds an attribute to the schema

If a +block+ is given, uses that to test against instead of +type+

Examples:

Add an attribute named foo, expecting a string


class MyMedia
  include MediaTypes::Dsl

  validations do
    attribute :foo, String
  end
end

MyMedia.valid?({ foo: 'my-string' })
# => true

Add an attribute named foo, expecting nested scheme


class MyMedia
  include MediaTypes::Dsl

  validations do
    attribute :foo do
      attribute :bar, String
    end
  end
end

MyMedia.valid?({ foo: { bar: 'my-string' }})
# => true

Parameters:

  • key (Symbol)

    the attribute name

  • opts (Hash)

    options to pass to Scheme or Attribute

  • type (Class, #===, Scheme) (defaults to: nil)

    The type of the value, can be anything that responds to #===, or scheme to use if no &block is given. Defaults to Object without a &block and to Hash with a &block. or scheme to use if no &block is given. Defaults to Object without a &block and to Hash with a &block.

Raises:

See Also:



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/media_types/scheme.rb', line 205

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

  type ||= ::Object

  if block_given?
    return collection(key, expected_type: ::Hash, optional: optional, **opts, &block)
  end

  if type.is_a?(Scheme)
    return rules.add(key, type, optional: optional)
  end

  rules.add(key, Attribute.new(type, **opts, &block), optional: optional)
end