In one controller I got a method that I want to refactor to share with other controllers. At the same time, I'm passing it to the callback before_action
.
app/models/meal_controller.rb
def check_for_user
token = request.headers[:token]
if token.nil?
render json: "Unathorized", status: 401
elsif @meal.user.auth_code != token
render json: "Forbidden", status: 403
end
end
So my approach was move check_for_user
to the ApplicationController and modify it as follows:
def check_for_user(item)
token = request.headers[:token]
if token.nil?
render json: "Unathorized", status: 401
elsif item.user.auth_code != token
render json: "Forbidden", status: 403
end
end
And back to the MealController, create a other "dummy" method without params and call the check_for_user.
def check_for_user_meal
check_for_user(@meal)
end
My question is: is there a better way to refactor this code?
Thanks in advance.