I have a model called a Message. I have a field called time_received_or_sent stored in the database. A message that is incoming would have a time_recieved and a message that is outgoing would have a time sent. No message would ever have both. Can I combine these in a model so that time_received and time_sent just point to that field when edited? I have four methods in my model that look pretty useless.
Model Message < ActiveRecord::Base
...
def time_received=(time_received)
time_received_or_sent = time_received
end
def time_received
return time_received_or_sent
end
def time_sent=(time_sent)
time_received_or_sent = time_sent
end
def time_sent
return time_received_or_sent
end
end
I would prefer something much shorter.
And I’m looking for something other than:
def time_sent; time_received_or_sent; end
def time_received; time_received_or_sent; end
def time_sent=(time_sent); time_received_or_sent=(time_sent); end
def time_received=(time_received); time_received_or_sent=(time_received); end
Although, if this is the best possible, then I’m fine with it.
You can always use
alias_methodto collapse these down:This is handy for avoiding duplicate implementations of the same method.