Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created September 1, 2011 17:22
Show Gist options
  • Save ahoward/1186689 to your computer and use it in GitHub Desktop.
Save ahoward/1186689 to your computer and use it in GitHub Desktop.
# build scopes for owners, producers, and viewers. each scope can be used
# with one, or more, users. for example:
#
# Organization.with_owners(jane, john)
#
{
:owner => %w'owner',
:producer => %w'owner producer',
:viewer => %w'owner producer viewer'
}.each do |name, roles|
scope_name = "with_#{ name }".pluralize
scope(scope_name, proc{ |*users|
ids = list_of_ids(users)
criteria = ids.map do |id|
{'memberships' => {'$elemMatch' => {'user_id' => id, 'roles' => {'$in' => roles}}}}
end
Organization.where('$and' => criteria)
})
(class << self; self; end).module_eval do
alias_method(scope_name.singularize, scope_name.pluralize)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment