diff --git a/app/models/user.rb b/app/models/user.rb index bf7e5d7..5b0a841 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -72,6 +72,19 @@ def name identifiers:) } + def self.by_name(full_name) + name_parts = full_name.split + first_name = name_parts.first + last_name_parts = name_parts[1..].join(' ') + query = User.where('unaccent(lower(first_name)) = unaccent(lower(?))', first_name.downcase) + + last_names_condition = last_name_parts.split.map do |part| + "unaccent(lower(last_name)) LIKE unaccent(lower('%#{part}%'))" + end.join(' OR ') + + query.where(last_names_condition) + end + def should_generate_new_friendly_id? true end diff --git a/db/schema.rb b/db/schema.rb index ae763ce..4f82751 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,10 +10,11 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 2024_03_25_040617) do +ActiveRecord::Schema[7.0].define(version: 2024_03_29_180055) do # These are extensions that must be enabled in order to support this database enable_extension "pg_stat_statements" enable_extension "plpgsql" + enable_extension "unaccent" create_table "assignments", force: :cascade do |t| t.float "coverage" diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 48eca71..17d8be3 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -103,4 +103,19 @@ expect(User.by_external_identifier(user.email).first).to eql(user) end end + + context '#by_name' do + let(:full_name) { 'Pedro Vieira GuimarĂ£es' } + + context 'when the user exists' do + it 'returns the user by the name' do + user = create(:user, first_name: 'Pedro', last_name: 'Vieira') + expect(User.by_name(full_name).first).to eql(user) + end + end + + it 'returns an active record query' do + expect(User.by_name(full_name)).to be_an(ActiveRecord::Relation) + end + end end