Thaddeus.net Blog

A random brain dump of ideas that are too long to be tweets

Adding a named_scope based on user preferences

I recently tackled the problem in Blankless of hiding last year's gift suggestions. The problem is that I wanted to apply a named scope based on the user preferences. Further complicating things, I couldn't simply refer to that named scope wherever I needed it, because that would have involved a) a lot of repeating myself and b) a lot of hunting through every file for every reference to gifts.

I needed to find a way to do the same thing as adding a defaultscope to the model in a beforefilter. But, you can't just do that because it applies to everyone and doesn't take effect until the model is reloaded.

The solution turned out to be to add a withscope in an aroundfilter as shown. This lets every call to the Gift model's finders be scoped if I need it to be.

Simple, obvious, and doesn't require changing any existing code, just added two methods.

blog comments powered by Disqus