module Virtus::TypeLookup
A module that adds type lookup to a class
Constants
- TYPE_FORMAT
Public Class Methods
extended(model)
click to toggle source
Set cache ivar on the model
@param [Class] model
@return [undefined]
@api private
# File lib/virtus/support/type_lookup.rb, line 15 def self.extended(model) model.instance_variable_set('@type_lookup_cache', {}) end
Public Instance Methods
determine_type(class_or_name)
click to toggle source
Returns a descendant based on a name or class
@example
MyClass.determine_type('String') # => MyClass::String
@param [Class, to_s] class_or_name
name of a class or a class itself
@return [Class]
a descendant
@return [nil]
nil if the type cannot be determined by the class_or_name
@api public
# File lib/virtus/support/type_lookup.rb, line 34 def determine_type(class_or_name) @type_lookup_cache[class_or_name] ||= determine_type_and_cache(class_or_name) end
primitive()
click to toggle source
Return the default primitive supported
@return [Class]
@api private
# File lib/virtus/support/type_lookup.rb, line 43 def primitive raise NotImplementedError, "#{self}.primitive must be implemented" end
Private Instance Methods
determine_type_and_cache(class_or_name)
click to toggle source
@api private
# File lib/virtus/support/type_lookup.rb, line 50 def determine_type_and_cache(class_or_name) case class_or_name when singleton_class determine_type_from_descendant(class_or_name) when Class determine_type_from_primitive(class_or_name) else determine_type_from_string(class_or_name.to_s) end end
determine_type_from_descendant(descendant)
click to toggle source
Return the class given a descendant
@param [Class] descendant
@return [Class]
@api private
# File lib/virtus/support/type_lookup.rb, line 68 def determine_type_from_descendant(descendant) descendant if descendant < self end
determine_type_from_primitive(primitive)
click to toggle source
Return the class given a primitive
@param [Class] primitive
@return [Class]
@return [nil]
nil if the type cannot be determined by the primitive
@api private
# File lib/virtus/support/type_lookup.rb, line 82 def determine_type_from_primitive(primitive) type = nil descendants.select(&:primitive).reverse_each do |descendant| descendant_primitive = descendant.primitive next unless primitive <= descendant_primitive type = descendant if type.nil? or type.primitive > descendant_primitive end type end
determine_type_from_string(string)
click to toggle source
Return the class given a string
@param [String] string
@return [Class]
@return [nil]
nil if the type cannot be determined by the string
@api private
# File lib/virtus/support/type_lookup.rb, line 102 def determine_type_from_string(string) if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS) const_get(string, *EXTRA_CONST_ARGS) end end