Module: Advisable
- Defined in:
- lib/more/facets/advice.rb
Instance Method Summary collapse
- #advice_after ⇒ Object
- #advice_around ⇒ Object
-
#advice_before ⇒ Object
class Module.
-
#advise(meth) ⇒ Object
Advise a method.
- #after(meth, &block) ⇒ Object
- #around(meth, &block) ⇒ Object
- #before(meth, &block) ⇒ Object
-
#method_added(meth) ⇒ Object
after :method_added do |meth| advise(meth) unless defined?(“#meth_orig”) end.
Instance Method Details
#advice_after ⇒ Object
91 92 93 |
# File 'lib/more/facets/advice.rb', line 91 def advice_after @advice_after ||= {} #Hash.new{|h,k| h[k] = []} end |
#advice_around ⇒ Object
95 96 97 |
# File 'lib/more/facets/advice.rb', line 95 def advice_around @advice_around ||= {} #Hash.new{|h,k| h[k] = []} end |
#advice_before ⇒ Object
class Module
87 88 89 |
# File 'lib/more/facets/advice.rb', line 87 def advice_before @advice_before ||= {} #Hash.new{|h,k| h[k] = []} end |
#advise(meth) ⇒ Object
Advise a method.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
# File 'lib/more/facets/advice.rb', line 119 def advise(meth) #return false if defined?(meth_origin) args = instance_method(meth).arguments module_eval(<<-END, __FILE__, __LINE__) alias_method '#{meth}_origin', '#{meth}' def #{meth}(#{args}) target = method!('#{meth}_origin') unless target.advised ancs = self.class.ancestors.select{ |anc| anc.respond_to?(:advice_before) } target.advice_before = ancs.collect{ |anc| anc.advice_before[:'#{meth}'] } target.advice_after = ancs.collect{ |anc| anc.advice_after[:'#{meth}'] } target.advice_around = ancs.collect{ |anc| anc.advice_around[:'#{meth}'] } target.advised = true end target.call_with_advice(self, *[#{args}]) end END end |
#after(meth, &block) ⇒ Object
105 106 107 108 109 |
# File 'lib/more/facets/advice.rb', line 105 def after(meth, &block) name = "#{meth}:after#{block.object_id}" define_method(name, &block) (advice_after[meth.to_sym] ||= []) << name end |
#around(meth, &block) ⇒ Object
111 112 113 114 115 |
# File 'lib/more/facets/advice.rb', line 111 def around(meth, &block) name = "#{meth}:around#{block.object_id}" define_method(name, &block) (advice_around[meth.to_sym] ||= []) << name end |
#before(meth, &block) ⇒ Object
99 100 101 102 103 |
# File 'lib/more/facets/advice.rb', line 99 def before(meth, &block) name = "#{meth}:before#{block.object_id}" define_method(name, &block) (advice_before[meth.to_sym] ||= []) << name end |
#method_added(meth) ⇒ Object
after :method_added do |meth|
advise(meth) unless defined?("#{meth}_orig")
end
147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/more/facets/advice.rb', line 147 def method_added(meth) return if meth == :method_added @added_stack ||= [] return if @added_stack.last == meth return if /_(origin)$/ =~ meth.to_s return if /:(before|after|around)/ =~ meth.to_s @added_stack << meth #return if instance_methods(false).include?("#{meth}_orig") advise(meth) @added_stack.pop end |