Skip to content

Instantly share code, notes, and snippets.

@rossta
Created October 17, 2012 10:27
Show Gist options
  • Select an option

  • Save rossta/3904856 to your computer and use it in GitHub Desktop.

Select an option

Save rossta/3904856 to your computer and use it in GitHub Desktop.
OrderedByCounter article
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