spree/spree — pull request #2608 by lilleyt (2013-02-25 17:08:14+00:00)
Title: Factor product scopes to allow simple scopes to be added from an extensi...

I wanted to add a simple product scope so I could sort products by the "available on" date.

When I looked at the Spree source, I saw that simple scopes are defined by an array with the scope names of the form "x_by_y", where x is the attribute to be sorted and y is the direction (ascending, descending).

It's followed by a bit of code which is immediately executed, which iterates over the list, parsing the names and acting appropriately to add the desired simple scope to the model.

Unfortunately, if you are trying to add your own simple scope, you can't simply add yours to the list via a decorator. By the time the decorator runs, the model is already defined, and the code which parses the list of names has been executed at that point. It can't be executed again since it is not packaged as a method, it is a run-once piece of code.

The only other option would be to copy the code from the model into your own code, or to override the model entirely. That's not very DRY.

This commit simply packages the bit of parsing code into a method, that's all. The code then immediately calls the method so it acts exactly as it did before.

From an extension, however, you can now use a decorator to make your own list of simple scopes and have them parsed by the same method which the model uses for itself. This seems like a simple and good refactor to me.

There is no issue opened, no tests (since there is no new internal behavior) and no mailing list discussion related to this. I just needed it and thought it made sense to submit.

I made this change on 1-3-stable and haven't assessed which other branches it might work on.

Thanks.