2

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.

4

1 回答 1

0

以下是一些相关链接: http ://www.ruby-forum.com/topic/95269 http://www.ruby-forum.com/topic/164588

基本上,一个模块只会被包含一次,但包含的回调可能会被多次调用。

于 2012-08-17T08:26:44.163 回答