Module: Tins::Eigenclass

Included in:
Object, ClassMethod
Defined in:
lib/tins/dslkit.rb

Overview

This module contains some handy methods to deal with eigenclasses. Those are also known as virtual classes, singleton classes, metaclasses, plus all the other names Matz doesn’t like enough to actually accept one of the names.

The module can be included into other modules/classes to make the methods available.

Examples:

Using eigenclass alias

class MyClass
  include Tins::Eigenclass
end

puts MyClass.eigenclass  # => MyClass singleton class

Instance Method Summary collapse

Instance Method Details

#eigenclass_class_eval { ... } ⇒ Object

Evaluates the block in context of the eigenclass’s class context.

This method allows you to define class methods on the eigenclass itself, which is different from eigenclass_eval that defines singleton methods on the object instance.

Examples:

Defining class methods on eigenclass

class MyClass
  include Tins::Eigenclass
end

obj = MyClass.new
obj.eigenclass_class_eval { def foo; "bar"; end }
obj.foo  # => "bar"

Yields:

  • The block to evaluate in the eigenclass’s class context

Returns:

  • (Object)

    The result of the last expression in the block



64
65
66
# File 'lib/tins/dslkit.rb', line 64

def eigenclass_class_eval(&block)
  eigenclass.class_eval(&block)
end

#eigenclass_eval {|obj| ... } ⇒ Object

Evaluates the block in context of the eigenclass of this object.

This method allows you to define singleton methods or access singleton class methods directly on an object.

Examples:

Defining class methods using attr_accessor on a class

class MyClass
  include Tins::Eigenclass
end

MyClass.eigenclass_eval { attr_accessor :foo }
MyClass.foo = "bar"
MyClass.foo  # => "bar"

Yields:

  • The block to evaluate in the eigenclass context

Yield Parameters:

  • obj (Object)

    The object whose eigenclass is being evaluated

Returns:

  • (Object)

    The result of the last expression in the block



42
43
44
# File 'lib/tins/dslkit.rb', line 42

def eigenclass_eval(&block)
  eigenclass.instance_eval(&block)
end