Skip to content

paulca/can_has

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Can Has?

Can Has? is a really really simple Rails plugins that adds a nice little helper method for checking a users permissions on a model. It allows you to write something like this:


  @post = Post.create!(:title => 'My post', :content => 'Interesting stuff')
  if user.can_read?(@post)
    ...show it
  else
    ...don't show it
  end

The basic premise is that if a model belongs to a user, that user and anyone else can read it, but only that user can do anything else.

Installation

Can has? is a Ruby on Rails plugin. Installation is as easy as:


  ./script/plugin install git://github.com/paulca/can_has.git

Example


class User < ActiveRecord::Base
  can_has?
end

class Post
  belongs_to :user
end

That’s it! Now, by default, anyone will be able to view the post:


  owner = User.first
  post = owner.posts.first
  owner.can_read?(post) # => true
  
  user = User.last
  user.can_read?(post) # => true

However, any other actions will return true for the owner and false for the user:


  owner = User.first
  post = owner.posts.first
  owner.can_edit?(post) # => true
  owner.can_delete?(post) # => true
  
  user = User.last
  user.can_read?(post) # => true
  user.can_edit?(post) # => false
  user.can_delete?(post) # => false

Extending

To extend the power of the can_* methods, just create them on the model that you want to check against:


  class User < ActiveRecord::Base
    can_has?
    
    def has_legs?
      true
    end
  end
  
  class Bicyle < ActiveRecord::Base
    belongs_to :user
    
    def can_ride?(user)
      return true if user.has_legs?
      return false
    end
  end
  
  @bicycle = Bicycle.create!
  @user = User.first
  
  @user.can_ride?(@bicycle) # => true

About me

I’m Paul Campbell. I’m a partner in Contrast (http://www.contrast.ie) and I work on Exceptional, a Ruby on Rails exception tracker (http://getexceptional.com).

Follow me on Twitter: http://www.twitter.com/paulca

Copyright © 2009 Paul Campbell, released under the MIT license

About

A simple ActiveRecord plugin to add a lovely little can_view, can_edit, can_delete permissions system in simple use cases

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published