Whenever splitting on delimiter prepare for white space or nil entries

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the user-input-and-output category.

Last Updated: 2021-05-16

The following code caused a failure in production:

def tag_list=(names)
 self.tags = names.split(',').map do |n|

   Tag.where(name: n.strip).first_or_create!
 end
end

The problem was that someone input the following as tags in the form "instruments, " (i.e. a trailing comma), and the code tried to create a blank tag.

The fix:

def tag_list=(names)
 self.tags = names.split(',').map do |n|
  next if n.blank?

   Tag.where(name: n.strip).first_or_create!
 end
end

Lesson

When splitting on delimiter (e.g. comma), anticipate a blank or nil entry.