Created
September 18, 2011 08:27
-
-
Save bradleypriest/1224877 to your computer and use it in GitHub Desktop.
Arel Scopes
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 ArelScopes | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# Create chainable arel scopes | |
# Example: | |
# class Post | |
# arel_scope :published, lambda { arel_table[:published_at].gteq(Time.now) } | |
# arel_scope :written_by, lambda { |user| arel_table[:author_id].eq(user.id) } | |
# arel_scope :approved, arel_table[:approved].eq(true) | |
# scope :viewable_by, lambda { |user| where(written_by_as_arel(user).or(published_as_arel.and(approved_as_arel))) | |
# .... | |
# | |
# Gives you: | |
# Post.published | |
# Post.written_by(User.find_by_username("Bill") | |
# Post.viewable_by(User.find(12)) | |
# Post.where( Post.published_as_arel.or(Post.approved_as_arel) | |
def arel_scope(name, arel_scope_options={}) | |
if arel_scope_options.is_a? Proc | |
scope(name, lambda { |*args| where(arel_scope_options.call(*args)) }) | |
scope_proc = arel_scope_options | |
else | |
scope(name, where(arel_scope_options) ) | |
scope_proc = lambda { arel_scope_options } | |
end | |
singleton_class.send(:redefine_method, (name.to_s+"_as_arel").to_sym, &scope_proc) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment