I was checking some code, and something similar to the following showed up:
def between_dates(date_1, date_2) if date_1 && date_2 conditions "created_at >= date_1 AND created_at <= date_2" elseif date_1 conditions "created_at >= date_1" elseif date_2 conditions "created_at <= date_2" end end
It looked the kind of code that could be improved, but I couldn't find a more elegant solution for such a trivial and common conditional statement.
I'm looking for a better answer for this problem when we must return a value for one, other or both.
I'd use something like this:
def between_dates(date_1, date_2) parts =  if date_1 parts << "created_at >= date_1" end if date_2 parts << "created_at <= date_2" end full = parts.join(' AND ') conditions(full) end
This can be further prettified in many ways, but you get the idea.