Skip to content

Instantly share code, notes, and snippets.

@rondy
Created October 14, 2011 13:16
Show Gist options
  • Save rondy/1287061 to your computer and use it in GitHub Desktop.
Save rondy/1287061 to your computer and use it in GitHub Desktop.
Dynamic scopes injection
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