Module: Anise::Annotative::Variables

Includes:
Anise::Annotations
Defined in:
lib/anise/annotative/variables.rb

Overview

I bet you never imagined Ruby could suport ‘@style` annotations. Well, I am here to tell you otherwise.

The VariableAnnotator module allows class instance variable to be used method annotations which attach to the next defined method.

class X
  extend Anise::Annotative::Variables

  variable_annotator :@doc
  variable_annotator :@returns

  @doc = "See what I mean?"
  @returns = NilClass

  def see
    puts "Yes, I see!"
  end
end

X.ann(:see, :@doc) #=> "See what I mean?"

This library uses the #method_added callback, so be sure to respect good practices of calling super if you need to override this method.

**IMPORTANT!!!** This library is an interesting expirement, but it remains to be determined if it makes sense for general use.

Instance Method Summary collapse

Methods included from Anise::Annotations

#ann, #ann!, #annotation_added, #annotations

Instance Method Details

#annotator(iv, &block) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/anise/annotative/variables.rb', line 58

def annotator(iv, &block)
  if not iv.to_s.start_with?('@')
    if defined?(super)
      super(iv, &block)
    else
      raise ArgumentError, "not a valid instance variable -- #{iv}"
    end
  else
    variable_annotator(iv, ns, &block)
  end
end

#method_added(sym) ⇒ Object

When a method is added, run all pending annotations.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/anise/annotative/variables.rb', line 73

def method_added(sym)
  @_variable_annotations ||= {}
  @_variable_annotations.each do |iv, block|
    if iv.to_s.index('/')
      iv, ns = iv.to_s.split('/')
    else
      ns = :ann
    end
    value = instance_variable_get(iv)
    if block
      block.call(sym, value)
    else
      ann(sym/ns, iv=>value)
    end
    # TODO: can we undefine the instance variable?
    instance_variable_set(iv, nil)
  end
  super(sym) if defined?(super)
end

#variable_annotator(iv, &block) ⇒ Object

Open method annotations.

Examples:

variable_annotator :@doc

Parameters:

  • ns (Symbol)

    Annotator to use. Default is ‘:ann`.



46
47
48
49
50
51
52
53
54
55
# File 'lib/anise/annotative/variables.rb', line 46

def variable_annotator(iv, &block)
  # TODO: should none iv raise an error instead?
  iv = "@#{iv}".to_sym if iv.to_s !~ /^@/

  # TODO: use an annotation to record the annotators
  #ann(:variable_annotator, iv=>block)

  @_variable_annotations ||= {}
  @_variable_annotations[iv] = block
end