So I tried to give ActiveSupport::Concern in an app that has been living since Rails 2.x. We only just upgraded it to Rails 3.0, then 3.1 and now we are rolling on 3.2.
I’ve always liked showing what I really do instead of showing examples and now I would like to follow Alexander Zaytsev example of showing production code.
While David Heinemeir Hanson talks about making your fat models slim with Concerns, I am going to use it to DRY up a piece of controller code I have laying around.
The app is an e-commerce webshop app that has a products listings (or catalog) view laying around in a few different places. There is some logic in some controller actions that sorts the products based on a few given things in the params hash.
Here is the legacy bulky controller
index action of our ProductsController before the refactoring:
There is some stuff in there that I won’t explain right now. If you want to know, please post a comment.
The bit I want to refactor is line 22-41 since I am also using the exact same duplicate code in an OrganizationsController that shows an account page with the same list, only with featured products in it.
Before refactoring I ended up with for the OrganizationsController:
As you can see, there is A LOT of bulky code in this controller as well that is being moved from the legacy shit it is to good code.
For this blog post, we are looking at line 39-58 that we are going to put in a concern.
Following new Rails 4 conventions I will create an
app/controllers/concerns/product_sortable_listing.rb with the ProductSortableListing module:
I created a private method
sort_products_from_params that takes the AREL relation and returns it, with potential ordering and sorting added based on what’s in the params.
Now, here’s the refactored after for the ProductsController and the OrganizationsController, but concerned.
I am still thinking about how to let someone know where a method lives. I solved that with a comment above the line now, but that feels as if I am telling something that should be implicit anyways. Do you have any good suggestions?