Created
October 14, 2011 13:16
-
-
Save rondy/1287061 to your computer and use it in GitHub Desktop.
Dynamic scopes injection
This file contains 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 BookScopes | |
def self.extended(base) | |
base.instance_exec &scope_definitions | |
end | |
def self.included(base) | |
base.class_exec &scope_definitions | |
end | |
def self.scope_definitions | |
lambda do | |
class << self | |
def most_recent | |
order("created_at DESC").limit(1) | |
end | |
end | |
end | |
end | |
end | |
class Book < ActiveRecord::Base | |
include BookScopes | |
belongs_to :library | |
end | |
Book.most_recent | |
# or | |
class Library < ActiveRecord::Base | |
has_many :books | |
def self.find_most_recent_books | |
books.scoped.extend(BookScopes).most_recent | |
end | |
end | |
Library.first.find_most_recent_books |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment