Created
November 15, 2017 21:32
-
-
Save beaugaines/f0d2b4fb28ccc5ab603bf4f7a6f5cf36 to your computer and use it in GitHub Desktop.
wiki policy refactor
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
class WikiPolicy < ApplicationPolicy | |
attr_reader :user, :wiki | |
def initialize(user, wiki) | |
@user = user | |
@wiki = wiki | |
end | |
def update? | |
user.present? | |
end | |
def manage_collaborators? | |
wiki.user == user && wiki.collaborators | |
end | |
class Scope | |
attr_reader :user, :scope | |
def initialize(user, scope) | |
@user = user | |
@scope = scope | |
end | |
def resolve | |
wikis = [] | |
if user.role == 'admin' | |
wikis = scope.all # if the user is an admin, show them all the wikis | |
elsif user.role == 'premium' | |
all_wikis = scope.all | |
all_wikis.each do |wiki| | |
if wiki.private == false || wiki.user == user || wiki.users.include?(user) | |
wikis << wiki # if the user is premium, only show them public wikis, or that private wikis they created, or private wikis they are a collaborator on | |
end | |
end | |
else # this is the lowly standard user | |
all_wikis = scope.all | |
wikis = [] | |
all_wikis.each do |wiki| | |
if wiki.private == false || wiki.users.include?(user) | |
wikis << wiki # only show standard users public wikis and private wikis they are a collaborator on | |
end | |
end | |
end | |
wikis # return the wikis array we've built up | |
end | |
end | |
end | |
# or better yet, using Ruby's Array#| - http://devdocs.io/ruby~2.4/array#method-i-7C: | |
class WikiPolicy < ApplicationPolicy | |
attr_reader :user, :wiki | |
def initialize(user, wiki) | |
@user = user | |
@wiki = wiki | |
end | |
def update? | |
user.present? | |
end | |
def manage_collaborators? | |
wiki.user == user && wiki.collaborators | |
end | |
class Scope | |
attr_reader :user, :scope | |
def initialize(user, scope) | |
@user = user | |
@scope = scope | |
end | |
def resolve | |
if user.admin? | |
scope.all # if the user is an admin, show them all the wikis | |
elsif user.premium? | |
scope.where(private: false) | user.wikis | user.wiki_collaborations | |
elsif user.standard? | |
scope.where(private: false) | user.wikis | |
else | |
scope.where(private: false) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment