Skip to content

Instantly share code, notes, and snippets.

@nickw
Created June 23, 2011 19:38
Show Gist options
  • Save nickw/1043436 to your computer and use it in GitHub Desktop.
Save nickw/1043436 to your computer and use it in GitHub Desktop.
Permissions Query
def viewable_by(user)
# An item is viewable if:
# 1. There are no permissions set
(!self.blocking_enabled? && !self.targeting_enabled?) ||
# 2. OR the user owns the item
(self.user_id == user.id) ||
# 3. OR the item is not blocked from the user
(self.blocking_enabled? && !self.blocked_ages.include?(user.age) && self.blocked_gender != user.gender) ||
# 4. OR the item is targeted at the user
(self.targeting_enabled? && (self.targeted_ages.empty? || self.targeted_ages.include?(user.age)) && (self.targeted_gender.blank? || self.targeted_gender == user.gender))
end
def self.viewable_by(user)
any_of(
{
:blocking_enabled => false,
:targeting_enabled => false
},
{
:user_id => user.id
},
{
:blocking_enabled => true,
:blocked_ages.ne => user.age,
:blocked_gender.ne => user.gender
},
{
:targeting_enabled => true,
:"targeted_ages.0.exists" => false,
},
{
:targeting_enabled => true,
:targeted_ages => user.age,
},
{
:targeting_enabled => true,
:targeted_gender => ""
},
{
:targeting_enabled => true,
:targeted_gender => user.gender
}
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment