Skip to content

Commit

Permalink
add user_by_name method
Browse files Browse the repository at this point in the history
  • Loading branch information
kaiomagalhaes committed Mar 29, 2024
1 parent e47a81d commit f17082a
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
13 changes: 13 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions spec/models/user_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit f17082a

Please sign in to comment.