Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SystemStackError in Ruby Exception Handling using Aquarium(Aspect Oriented Programming)

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
like image 263
Aravindan.ck Avatar asked Mar 27 '12 11:03

Aravindan.ck


2 Answers

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
like image 45
Guoliang Cao Avatar answered Oct 27 '22 05:10

Guoliang Cao


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.

like image 167
Ghoti Avatar answered Oct 27 '22 06:10

Ghoti