From bafaf9c7861185ede3ed849ef0fb6c83f9b3b32f Mon Sep 17 00:00:00 2001 From: Muhsin Keloth Date: Wed, 7 Feb 2024 12:42:53 +0530 Subject: [PATCH] feat: add `split_first_and_last_name` helper --- app/helpers/contact_helper.rb | 14 +++++++++ spec/helpers/contact_helper_spec.rb | 47 +++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 app/helpers/contact_helper.rb create mode 100644 spec/helpers/contact_helper_spec.rb diff --git a/app/helpers/contact_helper.rb b/app/helpers/contact_helper.rb new file mode 100644 index 000000000..1f89a69e2 --- /dev/null +++ b/app/helpers/contact_helper.rb @@ -0,0 +1,14 @@ +module ContactHelper + def split_first_and_last_name(full_name) + return { first_name: nil, last_name: nil } if full_name.nil? + + # Remove extra spaces and split the name + names = full_name.squish.split + + first_name = names.first || '' + + last_name = names.drop(1).join(' ') + + { first_name: first_name, last_name: last_name } + end +end diff --git a/spec/helpers/contact_helper_spec.rb b/spec/helpers/contact_helper_spec.rb new file mode 100644 index 000000000..47f959787 --- /dev/null +++ b/spec/helpers/contact_helper_spec.rb @@ -0,0 +1,47 @@ +require 'rails_helper' + +RSpec.describe ContactHelper do + describe '#split_first_and_last_name' do + it 'correctly splits a full name into first and last name' do + full_name = 'John Doe Smith' + expected_result = { first_name: 'John', last_name: 'Doe Smith' } + expect(helper.split_first_and_last_name(full_name)).to eq(expected_result) + end + + it 'handles single-word names correctly' do + full_name = 'Cher' + expected_result = { first_name: 'Cher', last_name: '' } + expect(helper.split_first_and_last_name(full_name)).to eq(expected_result) + end + + it 'handles an empty string correctly' do + full_name = '' + expected_result = { first_name: '', last_name: '' } + expect(helper.split_first_and_last_name(full_name)).to eq(expected_result) + end + + it 'handles multiple consecutive spaces correctly' do + full_name = 'John Doe Smith' + expected_result = { first_name: 'John', last_name: 'Doe Smith' } + expect(helper.split_first_and_last_name(full_name)).to eq(expected_result) + end + + it 'returns nil for first and last name when input is nil' do + full_name = nil + expected_result = { first_name: nil, last_name: nil } + expect(helper.split_first_and_last_name(full_name)).to eq(expected_result) + end + + it 'handles names with special characters correctly' do + full_name = 'John Doe-Smith' + expected_result = { first_name: 'John', last_name: 'Doe-Smith' } + expect(helper.split_first_and_last_name(full_name)).to eq(expected_result) + end + + it 'handles non-Latin script names correctly' do + full_name = '李 小龙' + expected_result = { first_name: '李', last_name: '小龙' } + expect(helper.split_first_and_last_name(full_name)).to eq(expected_result) + end + end +end