Class: CrossCut

Inherits:
Cut show all
Defined in:
lib/cuts/aop.rb

Overview

The cut that carries a class's aspects. It has a method for each method of the class, those defined later included, which calls the advice that are joined to it and then the method itself.

Methods that every object has, those of Object and Kernel, are left alone.

Constant Summary

Constants inherited from Cut

Cut::VERSION

Instance Attribute Summary

Attributes inherited from Cut

#base

Attributes inherited from Module

#cross_cut

Instance Method Summary collapse

Methods inherited from Module

#apply, #aspects, #cuts

Constructor Details

#initialize(base) ⇒ CrossCut

Returns a new instance of CrossCut.



133
134
135
136
137
138
# File 'lib/cuts/aop.rb', line 133

def initialize(base)
  @advices = {}
  super(base)
  cross_methods.each{ |sym| cross(sym) }
  watch
end

Instance Method Details

#advices(joinpoint) ⇒ Object

The advice that apply to a method, as a list of aspect and advice name. They are worked out on first use.



142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/cuts/aop.rb', line 142

def advices(joinpoint)
  @advices[joinpoint.name] ||= (
    list = []
    base.aspects.each do |aspect|
      aspect.points.each do |advice, matches|
        matches.each do |match|
          list << [aspect, advice] if joinpoint === match
        end
      end
    end
    list
  )
end

#cross(sym) ⇒ Object

Define the method that calls a method's advice.



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/cuts/aop.rb', line 163

def cross(sym)
  return if method_defined?(sym, false) || private_method_defined?(sym, false)

  crosscut = self
  base     = self.base

  visibility = (
    if base.private_method_defined?(sym)
      :private
    elsif base.protected_method_defined?(sym)
      :protected
    else
      :public
    end
  )

  define_method(sym) do |*args, **opts, &blk|
    jp = Joinpoint.new(self, base, sym, *args){ super(*args, **opts, &blk) }

    advices = crosscut.advices(jp)

    if advices.empty?
      super(*args, **opts, &blk)
    else
      target = jp
      advices.each do |(aspect, advice)|
        target = Target.new(aspect, advice, target)
      end
      target.call
    end
  end

  __send__(visibility, sym)
end

#reset ⇒ Object

Forget which advice apply to which methods. This is done when another aspect is applied.



158
159
160
# File 'lib/cuts/aop.rb', line 158

def reset
  @advices.clear
end