How to add exception handling to my before_action

I have a method before_action

:

def current_user
  @current_user ||= User.find(:id => session[:id])
end

      

And I am calling the method like this:

def get_food user
  food = Food.find(:id => user.id)
end

      

This is fine, but I want to add exception handling.

When the user is null, I want to use @current_user

:

def get_food user
  food = Food.find(if user is nil i want to use @current_user.id)
end

      

Of course I can write like this:

def get_food user
  if user.nil?
    food = Food.find(@current_user.id)
  else
    food = Food.find(user.id)    
end

      

Or is this the best way?

def get_food user
  food = Food.find(user == nil? @current_user.id : user.id)
end

      

I'm curious if there is a better way than adding a simple statement if

inside a parameter?

+3


source to share


6 answers


The shortest lines I can think of is something like this:

Food.find((user || current_user).id)
Food.find(user.try(:id) || current_user.id)
Food.find(user ? user.id : current_user.id)

      



Not sure if this is really a readability movement. I would prefer something like this:

def get_food(user)
  user ||= current_user
  Food.find(user.id)
end

      

+4


source


You can use the ternary operator to make it one line:



user ? Food.find(user.id) :  Food.find(@current_user.id)

      

0


source


What about arrays

food = Food.where(id: [@current_user.try(:id),user.id]).first

      

0


source


You can try this:

food = Food.find(user.nil? ? @current_user.id : user.id)

      

0


source


How about the default parameters?

def get_food(user = @current_user)
  food = Food.find(user.id)
end

      

It will work if you call it without a parameter

something.get_food # notice the method is called with no params

      

If you want it to work as well, if you pass nil

, you must also add:

def get_food(user = @current_user)
  food = Food.find((user || @current_user).id)
end

      

However, the strange thing is that products and users have the same ID ... Perhaps the correct query is:

food = Food.find_by_user_id((user || @current_user).id)

      

or, if users have more than one food:

foods = Food.where(user: (user || @current_user)) # rails 4, :user => (user || @current_user) for rails 3

      

0


source


Food.find(user.id rescue @current_user.id)

      

0


source







All Articles