class Attributor::Class

Public Class Methods

example(_context = nil, options: {}) click to toggle source
# File lib/attributor/types/class.rb, line 34
def self.example(_context = nil, options: {})
  @klass.nil? ? 'MyClass' : @klass.name
end
family() click to toggle source
# File lib/attributor/types/class.rb, line 52
def self.family
  'string'
end
load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, **_options) click to toggle source
# File lib/attributor/types/class.rb, line 13
def self.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, **_options)
  return value if value.is_a?(native_type)
  return @klass || nil if value.nil?

  # Must be given a String object or nil
  unless value.is_a?(::String) || value.nil?
    raise IncompatibleTypeError.new(context: context, value_type: value.class, type: self)
  end

  value = '::' + value if value[0..1] != '::'
  result = value.constantize

  # Class given must match class specified when type created using .of() method
  unless @klass.nil? || result == @klass
    raise LoadError, "Error loading class #{value} for attribute with " \
                     "defined class #{@klass} while loading #{Attributor.humanize_context(context)}."
  end

  result
end
native_type() click to toggle source
# File lib/attributor/types/class.rb, line 9
def self.native_type
  ::Class
end
of(klass) click to toggle source

Create a Class attribute type of a specific Class.

@param klass [Class] optional, defines the class of this attribute, if constant

@return anonymous class with specified type of collection members

@example Class.of(Factory)

# File lib/attributor/types/class.rb, line 46
def self.of(klass)
  ::Class.new(self) do
    @klass = klass
  end
end