From d6f51f0c740e0e997b7640f7ff809d3fa7837e71 Mon Sep 17 00:00:00 2001 From: Jonas Nicklas Date: Tue, 24 Jun 2014 01:40:35 +0200 Subject: [PATCH] Remove usage of Struct in README --- README.md | 60 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 11a6773..32c089e 100644 --- a/README.md +++ b/README.md @@ -54,21 +54,8 @@ class PostPolicy end ``` -As you can see, this is just a plain Ruby class. As a convenience, we can inherit -from Struct or use Struct.new to define the policy class: - -``` ruby -class PostPolicy < Struct.new(:user, :post) - def update? - user.admin? or not post.published? - end -end -``` - -You could also use the convenient -[attr_extras](https://github.com/barsoom/attr_extras) gem. - -Pundit makes the following assumptions about this class: +As you can see, this is just a plain Ruby class. Pundit makes the following +assumptions about this class: - The class has the same name as some kind of model class, only suffixed with the word "Policy". @@ -82,6 +69,17 @@ Pundit makes the following assumptions about this class: That's it really. +Usually you'll want to inherit from the application policy created by the +generator, or set up your own base class to inherit from: + +``` ruby +class PostPolicy < ApplicationPolicy + def update? + user.admin? or not post.published? + end +end +``` + Supposing that you have an instance of class `Post`, Pundit now lets you do this in your controller: @@ -161,8 +159,15 @@ particular user has access to. When using Pundit, you are expected to define a class called a policy scope. It can look something like this: ``` ruby -class PostPolicy < Struct.new(:user, :post) - class Scope < Struct.new(:user, :scope) +class PostPolicy < ApplicationPolicy + class Scope + attr_reader :user, :scope + + def initialize(user, scope) + @user = user + @scope = scope + end + def resolve if user.admin? scope.all @@ -190,6 +195,27 @@ Pundit makes the following assumptions about this class: some kind of result which can be iterated over. For ActiveRecord classes, this would usually be an `ActiveRecord::Relation`. +You'll probably want to inherit from the application policy scope generated by the +generator, or create your own base class to inherit from: + +``` ruby +class PostPolicy < ApplicationPolicy + class Scope < Scope + def resolve + if user.admin? + scope.all + else + scope.where(:published => true) + end + end + end + + def update? + user.admin? or not post.published? + end +end +``` + You can now use this class from your controller via the `policy_scope` method: ``` ruby