Skip to content

Integration with Pundit #481

Closed
Closed

Description

@ghn

Hello,

I know this has partially been reported already #171 but I think what proposed @ribordy is kinda nice. I would even imagine one step further like

class DemoResource
  attribute :name, :string, readable: :readable?, writable: :writable?
  attribute :role :string, readable: :readable?, writable: :writable?

  def readable?(attr)
    policy(model_instance).permitted_read_attributes.include?(attr)
  end

  def writable?(attr)
    policy(model_instance).permitted_write_attributes.include?(attr)
  end
end

class DemoPolicy
  def index
    # some logic
  end

  def update
    # some logic
  end

  def permitted_read_attributes = %i[name role]

  def permitted_write_attributes
    if user.admin?
      %i[name role]
    else
      %i[name]
    end
  end
end

That way we can leverage Pundit for what they call "permitted_attributes" too and have the read+write permissions at the same place => in the policy file, where I think it belongs.

Would that make sense?

Activity

  1. jkeen commented on Mar 18, 2025

    @jkeen
    Collaborator

    @ghn I think this would be great. Do you have time to work up a PR?

  2. added theissue type on Mar 18, 2025
  3. ghn commented on Apr 13, 2025

    @ghn
    Author

    While I was digging the code to add the feature, I found out that it's already there 😂 only the documentation is not up to date.
    We can do

    class DemoResource
      attribute :name, :string, readable: :readable?
      attribute :role :string, readable: :readable?
    
      def readable?(object, attr)
        DemoPolicy.new(context.current_user, object).permitted_read_attributes.include?(attr.to_sym)
      end
    end

    readable? accepts zero, one or two arguments, see: https://github.com/graphiti-api/graphiti/blob/main/lib/graphiti/util/serializer_attributes.rb#L85

    However the writable method does not accept any argument yet :(

  4. jkeen commented on Jul 29, 2026

    @jkeen
    Collaborator

    @ghn released in v1.12.0

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions