user4827489
user4827489

Reputation:

How to include switch case in this code

Hi I have written this code

class Ability
  include CanCan::Ability

  def initialize(employee)
    employee ||= Employee.new
    if employee[:role]== 'SUPER-ADMIN'
      can :manage, :all
    elsif employee[:role]== 'HR'
      can :manage, :Employee
      can :manage, :Interview
    elsif employee[:role]== 'INVENTORY'
      can :manage, :Inventory
    else
      can :read, :all
    end
  end
end 

Now I have to give switch case instead of if else condition something like this

case role
      when "SUPER-ADMIN"
        can :manage, :all
      when "HR"
        can :manage, :Employee
        can :manage, :Interview
      when "INVENTORY"
        can :manage, :Inventory
      when  "Employee"
        can :read, :all
    end

Please guide me how to do this. Thanks in advance

Upvotes: 0

Views: 54

Answers (1)

Surya
Surya

Reputation: 16012

You're almost there. You can make a small change in your case to make it work:

class Ability
  include CanCan::Ability

  def initialize(employee)
    employee ||= Employee.new
    case employee[:role]
    when 'SUPER-ADMIN'
      can :manage, :all
    when 'HR'
      can :manage, :Employee
      can :manage, :Interview
    when 'INVENTORY'
      can :manage, :Inventory
    else
      can :read, :all
    end
  end
end

Upvotes: 1

Related Questions