before_filter and with_scope

I will be speaking on the Rails Recipes Meetup here in Stockholm tomorrow. My topic will be on recipe 28 in Chads excellent book, how you can use with_scope to DRY your code.

Whilst I have looked quite deeply into the subject - it is quite small actually - there is one thing I have yet to find out. Chad mentions that you can use wrap your actions with scoping using a before_filter.

The thing is that the author of the patch for nested scopes provides a plugin to enable just that, but he uses an around filter which utilizes funky metaprogramming to do just that. He has a whole blog entry about it.

I’ve asked twice in the IRC channel without any answer, and I’ve posted a question on the books forum.

Does anybody know if a before_filter can be used?

  • del.icio.us
  • Digg
  • description
  • Technorati
  • Reddit

One Response to “before_filter and with_scope”

  1. Jon Tirsen Says:

    I’ve been digging into this too. No you can’t use either a beforefilter or an aroundfilter to do this using the public API. The problem is that aroundfilter’s in Rails aren’t actually aroundfilter’s they’re more like a before/around-filter combo. A real around_filter could do:

    class ScopingFilter def around DomainObject.with_scope(…) do yield # passes control to controller end end end

    But unfortunately Rails isn’t capable of that. So instead the plugin has to use module_eval to dive into the private parts of the domain object and chuck in a scope in the “before” part of the “around” filter then dive in again and yank it out in the “after” part.

    Ugly? Oh yeaaaah… Pretty brutal rummaging around with another objects private parts like that.

    Maybe it’s time somebody teaches Rails Core what “around” really means…

Leave a Reply