So I have the following code that I wanted to make a little more readable:
user = User.find_by_username(username)
user = User.new(credentials) if user.nil?
Essentially the first line is the default, the following line instantiates itself if it’s not already set.
Is there a way I can clean this up a bit and get it onto a single line of code? Something like this maybe:
user = User.find_by_username(username) || User.new(credentials)
Edit
I now realize the the code I provided does exactly what I need, sorry for wasting cyberspace but feel free to suggest alternative solutions.
Yes, what you wrote is exactly the correct answer.
You could also write it this way, if preferred:
Keep in mind that your first example will only assign the second value if the first one is
nil, but your second example and my example above will assign the second value on bothnilandfalse.EDIT: As mentioned by others, if you’re working with Active Record you could also use a dynamic attribute-based finder