This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the ruby category.
Last Updated: 2024-11-23
I had the following code (pay attention to the tracking_info
parameter)
def add_email_to_list(email:, tracking_info:)
EmailSubscriber.find_by(email: email) || EmailSubscriber.new(
email: email, **tracking_info
)
...
end
I called with the following
add_email_to_list(email: 'j@example.com', tracking_info: session[:tracking_info])
The key is that sometimes the session[:tracking_info]
was nil
. In this case the
function fails, not knowing how to apply **
to nil
.
Defaulting to an empty hash at point of call is needed to fix:
def add_email_to_list(email:, tracking_info:)
EmailSubscriber.find_by(email: email) || EmailSubscriber.new(
# New code in parentheses below:
email: email, **(tracking_info || {})
)
...
end