Created
October 17, 2012 10:27
-
-
Save rossta/3904856 to your computer and use it in GitHub Desktop.
OrderedByCounter article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module MyModule | |
| extend ActiveSupport::Concern | |
| # removed code that modified User when | |
| # including this module in Article | |
| end | |
| module OrderedByCounter | |
| extend ActiveSupport::Concern | |
| included do | |
| class_attribute :counter_cache_column | |
| scope :order_by_counter, lambda { order("#{self.counter_cache_column} DESC") } | |
| end | |
| module ClassMethods | |
| def counter_order_from(association_name) | |
| klass = association_name.to_s.camelize.constantize # Article | |
| self.counter_cache_column = klass.get_counter_cache | |
| end | |
| end | |
| end | |
| class User < ActiveRecord::Base | |
| include OrderedByCounter | |
| counter_order_from :article | |
| end | |
| # => User.order_by_counter | |
| # By including this module in User and declaring from where the | |
| # counter relationship comes, I've avoided creating side effects | |
| # and can more easily reason the origins of these methods |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment