Yaman ALTareh
Yaman ALTareh

Reputation: 286

how get action in ability block of cancan gem of ruby on rails?

I install cancan gem in rails app

and i have block in my ability.rb like this ...

can [:action1,:action2,:action3] ,Obj do |x|
  # I wante to get current action, like this
  if action == action1
    #do something
  end
end

And i do not want to separate each action in special block

how get current action in ability block ?

Upvotes: 2

Views: 355

Answers (2)

IdanDavidi
IdanDavidi

Reputation: 482

Exactly what I needed to do! I ended up with this solution:

[:action1, :action2].each do |action|
  can action, Obj do |x|
    puts "#{action}" # print the given action
  end
end

Upvotes: 1

okliv
okliv

Reputation: 3959

You can initialize Ability class instance method with action as variable:

#models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user, action)

    can action.to_sym, Obj do |x|
       #do something with your action (and user?)
    end

  end

end

Now you can initialize new ability passing current action to it:

#application_controller.rb

def current_ability
  @current_ability ||= Ability.new(current_user, params[:action])
end

and apply any rules using action name stored in default parameter :action

Upvotes: 1

Related Questions