Rails: side effect of including the same filter twice

236 views Asked by At

I have a gem I'm developing that is based around using filters on ApplicationController. It's basically for logging, and one of the modules defines an around filter like so:

module LogExceptionFilter
  self.included(base)
      base.around_filter :do_a_bunch_of_logging_stuff
  end

  def do_a_bunch_of_logging_stuff
      ...
  end
end

It happens to be an around filter where I deal with exception logging, but my question would apply for any filter.

So it's supposed to be used like this

class ApplicationController
    include LogExceptionFilter
end

So what I'm worried about is if someone does:

class ApplicationController
    include LogExceptionFilter
    include LogExceptionFilter
end

I don't want to execute do_a_bunch_of_logging_stuff twice. So first

1)If do_a_bunch_of_logging_stuff is included twice, will rails apply the filter twice?

2)Is it my responsibility to protect the user from doing this? I could do so with a class variable, something like:

module LogExceptionFilter

  class << self
     cattr_accessor :filter_loaded
  end

  self.included(base)
    unless filter_loaded
      base.around_filter :do_a_bunch_of_logging_stuff
      filter_loaded = true
    end
  end

  def do_a_bunch_of_logging_stuff
      ...
  end
end

This variable is not thread safe so it's something that I'd want to be careful about putting in. But I don't want to write a library that can be easily broken. Thanks.

1

There are 1 answers

0
ronalchn On

Here are some relevant links: http://www.ruby-forum.com/topic/95269 http://www.ruby-forum.com/topic/164588

Basically, a module will only be included once, but the included callback may be called multiple times.