Class: Object

Inherits:
BasicObject
Extended by:
GollyUtils::AttrDeclarative
Defined in:
lib/golly-utils/ruby_ext/deep_dup.rb,
lib/golly-utils/ruby_ext/classes_and_types.rb

Defined Under Namespace

Classes: TypeValidationError

Instance Method Summary collapse

Methods included from GollyUtils::AttrDeclarative

attr_declarative

Instance Method Details

#deep_dupObject

Creates a deep copy of the object. Where supported (arrays and hashes by default), object state will be duplicated and used, rather than the original and duplicate objects sharing the same state.



4
5
6
# File 'lib/golly-utils/ruby_ext/deep_dup.rb', line 4

def deep_dup
  dup
end

#superclassesArray<Class>

Returns the class hierarchy of a given instance or class.

Examples:

Fixnum.superclasses  # <= [Fixnum, Integer, Numeric, Object, BasicObject]
100.superclasses     # <= [Fixnum, Integer, Numeric, Object, BasicObject]

Returns:

  • (Array<Class>)

    An array of classes starting with the current class, descending to BasicObject.



45
46
47
48
49
50
51
52
53
# File 'lib/golly-utils/ruby_ext/classes_and_types.rb', line 45

def superclasses
  if self == BasicObject
    [self]
  elsif self.is_a? Class
    [self] + self.superclass.superclasses
  else
    self.class.superclasses
  end
end

#validate_type!(name = nil, *valid_classes) ⇒ self

Validates the type of the current object.

Examples:

3     .validate_type nil, Numeric
nil   .validate_type nil, Numeric
'What'.validate_type nil, Numeric   # <= raises TypeValidationError

# Ensures that f_debug is boolean
f_debug.validate_type! 'the debug flag', true, false

Parameters:

  • name (nil|Symbol|String) (defaults to: nil)

    The name of the object being checked (i.e. self). This only used in the error message and has no functional impact.

  • valid_classes (Array<Class>)

    One or more classes that this object is allowed to be. Ruby primatives will automatically be translated to the corresponding class.

Returns:

  • (self)

    If validation passes.

Raises:

See Also:



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/golly-utils/ruby_ext/classes_and_types.rb', line 77

def validate_type!(*args)
  name= args.first.is_a?(String) || args.first.is_a?(Symbol) ? args.shift : nil
  classes= args.map{|a| RUBY_PRIMATIVE_CLASSES[a] || a }
  raise "You must specify at least one valid class." if classes.empty?

  unless classes.any?{|c| self.is_a? c }
    for_name= name ? " for #{name}" : ''
    raise TypeValidationError, "Invalid type#{for_name}: #{self.class}\nValid types are: #{classes.map(&:to_s).sort.join ', '}."
  end
  self
end