diff options
author | William George <code@williamgeorge.co.uk> | 2018-10-18 12:06:44 +0300 |
---|---|---|
committer | Sean McGivern <sean@mcgivern.me.uk> | 2018-10-18 12:06:44 +0300 |
commit | 1b153d497b6948932b0de2f0088fe7192eb0994a (patch) | |
tree | a4f93a1c3a12314b54b2486d5b471c929d4e7003 /app/finders/user_finder.rb | |
parent | c5d8e7fcee6bb15376902e8f1336f1ed368b9da8 (diff) |
Make getting a user by the username case insensitive
Diffstat (limited to 'app/finders/user_finder.rb')
-rw-r--r-- | app/finders/user_finder.rb | 52 |
1 files changed, 41 insertions, 11 deletions
diff --git a/app/finders/user_finder.rb b/app/finders/user_finder.rb index 815388c894e..556be4c4338 100644 --- a/app/finders/user_finder.rb +++ b/app/finders/user_finder.rb @@ -7,22 +7,52 @@ # times we may want to exclude blocked user. By using this finder (and extending # it whenever necessary) we can keep this logic in one place. class UserFinder - attr_reader :params + def initialize(username_or_id) + @username_or_id = username_or_id + end + + # Tries to find a User by id, returning nil if none could be found. + def find_by_id + User.find_by_id(@username_or_id) + end - def initialize(params) - @params = params + # Tries to find a User by id, raising a `ActiveRecord::RecordNotFound` if it could + # not be found. + def find_by_id! + User.find(@username_or_id) end - # Tries to find a User, returning nil if none could be found. - # rubocop: disable CodeReuse/ActiveRecord - def execute - User.find_by(id: params[:id]) + # Tries to find a User by username, returning nil if none could be found. + def find_by_username + User.find_by_username(@username_or_id) end - # rubocop: enable CodeReuse/ActiveRecord - # Tries to find a User, raising a `ActiveRecord::RecordNotFound` if it could + # Tries to find a User by username, raising a `ActiveRecord::RecordNotFound` if it could # not be found. - def execute! - User.find(params[:id]) + def find_by_username! + User.find_by_username!(@username_or_id) + end + + # Tries to find a User by username or id, returning nil if none could be found. + def find_by_id_or_username + if input_is_id? + find_by_id + else + find_by_username + end + end + + # Tries to find a User by username or id, raising a `ActiveRecord::RecordNotFound` if it could + # not be found. + def find_by_id_or_username! + if input_is_id? + find_by_id! + else + find_by_username! + end + end + + def input_is_id? + @username_or_id.is_a?(Numeric) || @username_or_id =~ /^\d+$/ end end |