I have module saved in lib/rolify_roles.rb
module RolifyRoles
path = File.join(Rails.root, 'config', 'rolify_roles.yml')
@config = YAML.load_file(path)
def add_role(role, target = nil)
raise "Role is not defined!" if RolifyRoles.config[role].nil?
...
end
end
This lib is prepended by models/user.rb
which using the add_role
method.
Then in controllers/users_controller.rb
i have method which uses the add_role
method:
def create_user_role
authorize User
role = params[:user][:rolify_role].to_sym
resource_type = params[:user][:resource_type]
resource_id = params[:user][:id]
resource = nil
resource = resource_type.constantize.find(resource_id) unless resource_type.blank? || resource_id.blank?
respond_to do |format|
if @user.add_role role, resource
format.html { redirect_to @user, notice: "Role #{role} was successfully added." }
format.json { render :show, status: :created, location: @user }
else
format.html { render :show }
format.json { render json: @call.errors, status: :unprocessable_entity }
end
end
# Add_role exceptions
rescue Exception => e
format.html { render :show }
format.json { render json: @call.errors, status: :unprocessable_entity }
end
I am trying to catch the exception from the module RolifyRoles
in the controller method.
But when the exception is raised (Role is not defined!
) it ends up in the module and it's not handled by the controller.
User#add_role lib/rolify_roles.rb, line 31
How can I handle this behavior in the controller?
Edit:
I've tried to rescue
from RecordNotFound
error in controller like this:
def create_user_role
authorize User
role = params[:user][:rolify_role].to_sym
resource_type = params[:user][:resource_type]
resource_id = params[:user][:id]
# Catch RecordNotFound doesn't work
begin
resource = nil
resource = resource_type.constantize.find(resource_id) if RolifyRoles.available_resources.include?(resource_type) && resource_id.present?
rescue ActiveRecord::RecordNotFound => e
format.html { render :show }
flash[:error] = e.message
end
end
And when the resource_type.constantize.find(resource_id)
cannot find the record, its doesnt raise the rescue
block.
Completed 500 Internal Server Error in 46ms (ActiveRecord: 3.2ms)
ActiveRecord::RecordNotFound - Couldn't find RequestComment with 'id'=1:
app/controllers/users_controller.rb:58:in `create_user_role'