Follow-up from "Sort contributed projects on profile page by last_activity_at"
The following discussion from !144443 (merged) should be addressed:
-
@abdwdd started a discussion: (+1 comment) suggestion (non-blocking): We should avoid adding too many params to a method. We don't have specific guidelines related to finders but I feel that the general structure should be similar to the service classes.
The main points are:
- All the parameters should be passed to the constructor.
-
params
contains the hash with properties. - Use the
params[:sort]
to find the sort order.
The resulting code will be more readable. Here's a basic refactor I made:
Click to expand
# frozen_string_literal: true # Finds the projects "user" contributed to, limited to either public projects # or projects visible to the given user. # # Arguments: # current_user: When given the list of the projects is limited to those only # visible by this user. # params: # 1. ignore_visibility [boolean] - When true the list of projects will include all contributed projects, # regardless of their visibility to the current_user. # 2. sort [string] - In the format `field_direction` like `id_desc`. Default is `id_desc`. class ContributedProjectsFinder < UnionFinder def initialize(user, current_user: nil, params: {}) @user = user @current_user = current_user @params = params end def execute # Do not show contributed projects if the user profile is private. return Project.none unless can_read_profile? projects = find_union(all_projects, Project) sort(projects).with_namespace end private attr_reader :user, :current_user, :params def can_read_profile? Ability.allowed?(current_user, :read_user_profile, user) end def all_projects return [user.contributed_projects] if params[:ignore_visibility] projects = [] projects << user.contributed_projects.visible_to_user(current_user) if current_user projects << user.contributed_projects.public_to_user(current_user) projects end def sort(projects) params[:sort] ||= 'id_desc' projects.sort_by_attribute(params[:sort]) end end
Doing this means a couple of other places would have to be updated where we are using this finder.