Module: Tins::Annotate

Included in:
Module
Defined in:
lib/tins/annotate.rb

Overview

A module for adding annotations to classes and methods

This module provides functionality to add metadata annotations to classes and methods, allowing for enhanced documentation and introspection capabilities

Instance Method Summary collapse

Instance Method Details

#annotate(name) ⇒ Object

The annotate method sets up annotation functionality for a given name by defining methods to set and retrieve annotations on class methods

Parameters:

  • name (Symbol)

    the name of the annotation to define



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/tins/annotate.rb', line 11

def annotate(name)
  singleton_class.class_eval do
    define_method(name) do |annotation = :annotated|
      instance_variable_set "@__annotation_#{name}__", annotation
    end

    define_method("#{name}_of") do |method_name|
      __send__("#{name}_annotations")[method_name]
    end

    define_method("#{name}_annotations") do
      if instance_variable_defined?("@__annotation_#{name}_annotations__")
        instance_variable_get "@__annotation_#{name}_annotations__"
      else
        instance_variable_set "@__annotation_#{name}_annotations__", {}
      end
    end

    old_method_added = instance_method(:method_added)
    define_method(:method_added) do |method_name|
      old_method_added.bind(self).call method_name
      if annotation = instance_variable_get("@__annotation_#{name}__")
        __send__("#{name}_annotations")[method_name] = annotation
      end
      instance_variable_set "@__annotation_#{name}__", nil
    end
  end

  define_method("#{name}_annotations") do
    self.class.__send__("#{name}_annotations")
  end

  define_method("#{name}_of") do |method_name|
    self.class.__send__("#{name}_of", method_name)
  end
end