Skip to content

Instantly share code, notes, and snippets.

@ramontayag
Created June 16, 2011 03:38
Show Gist options
  • Save ramontayag/1028632 to your computer and use it in GitHub Desktop.
Save ramontayag/1028632 to your computer and use it in GitHub Desktop.
How I integrated cancan into a widget
class MenuEditor::Page::FormWidget < Apotomo::Widget
# Step 1: make sure the current_user variable (or something like it) is available for use
include Devise::Controllers::Helpers
helper_method :current_user
responds_to_event :submit
def display
...
end
def submit(event)
# Step 3: call `current_ability.authorize!` like you would `authorize!` in a controller
current_ability.authorize! :manage, @current_site
@nav_item = @current_site.nav_items.new params[:nav_item]
...
end
private
def setup!(*)
@current_site ||= options[:current_site]
end
# Step 2: instantiate Ability with passing the current_user
def current_ability
::Ability.new current_user
end
end
@ramontayag
Copy link
Author

You can also add:

def can?(action, object)
  current_ability.can? action, object
end

Then make that method a helper:

helper_method :can?

So that you can do this in your views:

- if can? :purchase, @product

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