Method: MediaTypes::Scheme#attribute

Defined in:
lib/media_types/scheme.rb

#attribute(key, type = ::Object, 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: ::Object)

    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:



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/media_types/scheme.rb', line 161

def attribute(key, type = ::Object, optional: false, **opts, &block)
  raise KeyTypeError, "Unexpected key type #{key.class.name}, please use either a symbol or string." unless key.is_a?(String) || key.is_a?(Symbol)
  raise DuplicateKeyError, "An attribute with key #{key.to_s} has already been defined. Please remove one of the two." if rules.has_key?(key)
  raise DuplicateKeyError, "A string attribute with the same string representation as the symbol :#{key.to_s} already exists. Please remove one of the two." if key.is_a?(Symbol)&& rules.has_key?(key.to_s)
  raise DuplicateKeyError, "A symbol attribute with the same string representation as the string '#{key}' already exists. Please remove one of the two." if key.is_a?(String) && rules.has_key?(key.to_sym)

  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