Skip to content

Instantly share code, notes, and snippets.

@the-teacher
Created November 29, 2019 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save the-teacher/05a7f85237c756c4560017d31491597e to your computer and use it in GitHub Desktop.
Save the-teacher/05a7f85237c756c4560017d31491597e to your computer and use it in GitHub Desktop.
roles-post-1
class PostsController < ApplicationController
def index
# ...
end
def show
# ...
end
def create
# ...
end
def update
@post = @current_user.posts.find(params[:id])
@post.update!(post_params)
redirect_to @post
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
@the-teacher
Copy link
Author

@the-teacher
Copy link
Author

module Post
  class AuthorAbilities
    include Kan::Abilities

    role(:author) do |user, post|
      user.id == post.author_id
    end

    register(:read, :edit) { |_, _| true }
    register(:delete) { |_, _| false }
  end

  class AdminAbilities
    include Kan::Abilities

    role(:admin) do |user, _|
      user.admin?
    end

    register(:read, :edit, :delete) { |_, _| true }
  end
end

class UserPolicy
  attr_reader :current_user, :model

  def initialize(current_user, model)
    @current_user = current_user
    @user = model
  end

  def index?
    @current_user.admin?
  end

  def show?
    @current_user.admin? or @current_user == @user
  end

  def update?
    @current_user.admin?
  end

  def destroy?
    return false if @current_user == @user
    @current_user.admin?
  end
end

require 'cancancan'

class Ability
  include CanCan::Ability

  def initialize(user)
    send("#{user.role}_abilities", user)
  end

  def admin_abilities(user)
    can :manage, :all
  end

  def member_abilities(user)
    can :read, :all
    can :manage, Article, { author_id: user.id }
    can [:read, :update], User, { id: user.id }
  end

  def visitor_abilities(user)
    can :read, :all
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment