Class: UserFinder

Inherits:
Object
  • Object
show all
Defined in:
app/finders/user_finder.rb

Overview

A simple finding for obtaining a single User.

While using `User.find_by` directly is straightforward, it can lead to a lot of code duplication. Sometimes we just want to find a user by an ID, other 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.

Instance Method Summary collapse

Constructor Details

#initialize(username_or_id) ⇒ UserFinder

Returns a new instance of UserFinder.


10
11
12
# File 'app/finders/user_finder.rb', line 10

def initialize(username_or_id)
  @username_or_id = username_or_id
end

Instance Method Details

#find_by_idObject

Tries to find a User by id, returning nil if none could be found.


15
16
17
# File 'app/finders/user_finder.rb', line 15

def find_by_id
  User.find_by_id(@username_or_id)
end

#find_by_id!Object

Tries to find a User by id, raising a `ActiveRecord::RecordNotFound` if it could not be found.


21
22
23
# File 'app/finders/user_finder.rb', line 21

def find_by_id!
  User.find(@username_or_id)
end

#find_by_id_or_usernameObject

Tries to find a User by username or id, returning nil if none could be found.


37
38
39
40
41
42
43
# File 'app/finders/user_finder.rb', line 37

def find_by_id_or_username
  if input_is_id?
    find_by_id
  else
    find_by_username
  end
end

#find_by_id_or_username!Object

Tries to find a User by username or id, raising a `ActiveRecord::RecordNotFound` if it could not be found.


47
48
49
50
51
52
53
# File 'app/finders/user_finder.rb', line 47

def find_by_id_or_username!
  if input_is_id?
    find_by_id!
  else
    find_by_username!
  end
end

#find_by_usernameObject

Tries to find a User by username, returning nil if none could be found.


26
27
28
# File 'app/finders/user_finder.rb', line 26

def find_by_username
  User.find_by_username(@username_or_id)
end

#find_by_username!Object

Tries to find a User by username, raising a `ActiveRecord::RecordNotFound` if it could not be found.


32
33
34
# File 'app/finders/user_finder.rb', line 32

def find_by_username!
  User.find_by_username!(@username_or_id)
end

#input_is_id?Boolean

Returns:

  • (Boolean)

55
56
57
# File 'app/finders/user_finder.rb', line 55

def input_is_id?
  @username_or_id.is_a?(Numeric) || @username_or_id =~ /^\d+$/
end