Repository is archived
No commit activity in last 3 years
No release in over 3 years
A Rails validator based on CanCan.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.7
~> 10.0
>= 0

Runtime

 Project Readme

activemodel-can_validator

Build Status Code Climate Coverage Status Dependency Status

Validate user permissions with CanCan API.

Usage

Add to your Gemfile:

gem 'activemodel-can_validator'

Run:

bundle install

Then add the followng to your model which belongs to a user:

validates :user, can: { create: true }, on: :create

Sample

A user can retweet other users' tweets unless she is blocked by the user.

class User < ActiveRecord::Base
  has_many :retweets

  def block?(user)
    blocking_users.include?(user)
  end

  delegate :can?, :cannot?, to: :ability

  def ability
    @ability ||= Ability.new(self)
  end

  class Ability
    include CanCan::Ability
    
    def initialize(user)
      user ||= User.new
  
      can :create, Retweet do |retweet|
        !retweet.tweet.user.block?(user)
      end
    end
  end
end

class Tweet < ActiveRecord::Base
  belongs_to :user
end

class Retweet < ActiveRecord::Base
  belongs_to :user
  belongs_to :tweet
  validates :user, presence: true, can: { create: true }, on: :create
end