ユーザーの権限管理をしてくれるauthorityというGemを試してみました。
初期設定
いつものようにBundlerでインストールします。
gem 'authority'
下コマンドで初期設定をします。
rails g authority:install
使い方
準備
UserモデルとCommentモデルを作成して以下のように記述します。
class User < ActiveRecord::Base include Authority::UserAbilities end
class Comment < ActiveRecord::Base include Authority::Abilities self.authorizer_name = 'CommentAuthorizer' end
app/authorizers
以下にcomment_authorizer.rbを作成します。
class CommentAuthorizer < ApplicationAuthorizer def self.creatable_by?(user) true end end
Authority使ってみる
userのcan_create?にCommentを渡すとCommentAuthorizerのcreatable_by?の結果が返ってきます。
class CommentsController < ApplicationController def index if User.new.can_create?(Comment) # ..... end @comments = Comment.all end end
Commentのcreatable_by?メソッドやCommentAuthorizerのcreatable_by?メソッドを呼び出しても同じ結果になります。
Comment.new.creatable_by?(User.new) CommentAuthorizer.new.creatable_by?(User.new)