Module: Annotations

Included in:
Spider::Controller
Defined in:
lib/spiderfw/utils/annotations.rb

Overview

Module to allow annotations on methods. When included into a Class or Module, will make the Annotations::ClassMethods.__ and Annotations::ClassMethods.___ methods available. These can be used before a method to add annotations. The including class can also use Annotations::ClassMethods.define_annotation to define code that will be executed when an annotation is encountered.

Example:

class A
  include Annotations

  def self.cool_methods; @cool_methods ||= []; end

  define_annotation :method_rating do |klass, method, args|
    klass.cool_methods << method if args[0] == :cool
  end

  __.is_first_method
  def method1
  end

___.is_other_method
  def method2
  end

  __.method_rating :cool
  def method3
  end

end

p A.annotations[:method1] => {:is_first_method => true} 
p A.annotations[:method3] => {:is_other_method => true, :method_rating => :cool}
p A.cool_methods => [:method3]

Warning: annotations are not thread safe; if more than one file is being loaded at the same time for the same Module, annotations may end up wrong. You should ensure that all code using annotations is loaded in a single thread (this is usually a good idea anyway).

Defined Under Namespace

Modules: ClassMethods Classes: Annotator

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/spiderfw/utils/annotations.rb', line 41

def self.included(klass)
    klass.extend(ClassMethods)
    unless klass.is_a?(Class)
        klass.instance_eval do
            alias annotations_original_append_features append_features
            def append_features(kl)
                result = annotations_original_append_features(kl)
                if (@defined_annotations)
                    @defined_annotations.each do |name, proc|
                        kl.define_annotation(name, &proc)
                    end
                end
                @annotations ||= {}
                @annotations.each do |method, vals|
                    vals.each do |k, args|
                        args = [args] unless args.is_a?(Array)
                        kl.annotate(method, k, *args)
                    end
                end
                result
            end
        end
    end
    super
end