I'm trying to handle exceptions using AOP in Ruby. The toolkit i've used here is Aquarium(http://aquarium.rubyforge.org/).
I've written a sample code which will try to map all descendents(subclasses) of ApplicationController class written down.
On executing the following program, I get a SystemStackError(I also tried setting stack limit using "ulimit -s"). Someone please help me with this!. Or any suggestions on mapping :all_methods of subclasses of a superclass are welcome.. Thanks in advance.
require 'aquarium'
include Aquarium::Aspects
class ApplicationController
end
class Abc < ApplicationController
def func
puts "func called"
raise Exception.new # SystemStackError is thrown before reaching place
end
end
#Dummy class
class Def < ApplicationController
end
Aspect.new :after_raising => Exception,
:in_types_and_descendents => "ApplicationController" do |jp, object, *args|
puts "Exception Handling Code"
end
a = Abc.new
a.func
You could use my little gem - aspector, to achieve this too.
Using aspector, aspects are regular ruby classes, in which you define logic before/after/around method execution. Aspects can be tested independently, and be applied to classes. I've included code example below but a complete example can be found here
class ExceptionHandler < Aspector::Base
around options[:methods] do |proxy, *args, &block|
begin
proxy.call *args, &block
rescue Exception => e
puts "Exception Handling Code"
end
end
end
ExceptionHandler.apply Abc, :methods => Abc.instance_methods
a = Abc.new
a.func
You've been mandated to use a method that only makes sense for languages like Java, that don't have modules (or Scala's traits)? You can get this without any extra work by including the module where you need it with self.send :include or similar, as long as you've required the module file.
In any event I suggest you read Avdi Grimm's Exceptional Ruby to understand how exceptions work in Ruby - again not the same as Java - as has been pointed out.
Ruby doesn't need dependency injection - it's completely contra to the philosophy of the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With