Module: Anise::Annotation
- Defined in:
- lib/anise/annotation.rb
Overview
The Annotate module is the core of the Anise system. It provides the framework for annotating class or module related objects, typically symbols representing methods, with arbitrary metadata. These annotations do not do anything in themselves. They are simply data. But they can be put to good use. For instance an attribute validator might check for an annotation called :valid and test against it.
Synopsis
require 'anise/annotation'
class X
include Anise::Annotation
attr :a
ann :a, :desc => "A Number"
end
X.ann(:a, :desc) #=> "A Number"
As stated, annotations need not only annotate methods, they are arbitrary, so they can be used for any purpose. For example, we may want to annotate instance variables.
class X
include Anise::Annotation
ann :@a, :valid => lambda{ |x| x.is_a?(Integer) }
def validate
instance_variables.each do |iv|
if validator = self.class.ann(iv)[:valid]
value = instance_variable_get(iv)
unless validator.call(value)
raise "Invalid value #{value} for #{iv}"
end
end
end
end
end
Or, we could even annotate the class itself.
class X
include Anise::Annotate
ann self, :valid => lambda{ |x| x.is_a?(Enumerable) }
end
Although annotations are arbitrary they are tied to the class or module they are defined against.
– TODO: By using a global variable rather the definining a class
instance variable for each class/module, it is possible to
quicky scan all annotations for the entire system. To do
the same without this would require scanning through
the ObjectSpace. Should we do this?
$annotations = Hash.new { |h,k| h[k] = {} }
TODO: The ann(x).name notation is kind of nice. Would like to add that
back-in if reasonable. This would require @annotations to be an
OpenHash or OpenObject rather than just a Hash though.
++
Defined Under Namespace
Modules: Aid
Class Method Summary collapse
Class Method Details
.included(base) ⇒ Object
72 73 74 |
# File 'lib/anise/annotation.rb', line 72 def self.included(base) base.extend Aid end |