Accessing Request Data

ryanb edited this page Aug 13, 2010 · 1 revision

What if you need to modify the permissions based on something outside of the User object? For example, let's say you want to blacklist certain IP addresses from creating comments. The IP address is accessible through request.remote_ip but the Ability class does not have access to this. It's easy to modify what you pass to the Ability object by overriding the current_ability method in ApplicationController.

class ApplicationController < ActionController::Base


  def current_ability, request.remote_ip)

class Ability
  include CanCan::Ability

  def initialize(user, ip_address)
    can :create, Comment do |comment|
      # check if ip_address is bad

This concept can apply to session and cookies as well.

You may wonder, why I pass only the IP Address instead of the entire request object? I prefer to pass only the information needed, this makes testing and debugging the behavior easier.