labels_finder.rb 1.54 KB
Newer Older
1
class LabelsFinder < UnionFinder
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
2
3
4
5
6
7
  def initialize(current_user, params = {})
    @current_user = current_user
    @params = params
  end

  def execute
8
    items = find_union(label_ids, Label)
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
9
10
11
12
13
14
15
16
    items = with_title(items)
    sort(items)
  end

  private

  attr_reader :current_user, :params

17
  def label_ids
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
18
    label_ids = []
19
20
21
22
23
24
25
26
27
28

    if project
      label_ids << project.group.labels if project.group.present?
      label_ids << project.labels
    else
      label_ids << Label.where(group_id: projects.group_ids)
      label_ids << Label.where(project_id: projects.select(:id))
    end

    label_ids
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
29
30
  end

31
32
33
34
  def sort(items)
    items.reorder(title: :asc, type: :desc)
  end

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
35
36
37
38
39
  def with_title(items)
    items = items.where(title: title) if title.present?
    items
  end

40
41
  def group_id
    params[:group_id].presence
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
42
43
44
45
46
47
  end

  def project_id
    params[:project_id].presence
  end

48
49
50
51
  def project_ids
    params[:project_ids].presence
  end

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
52
53
54
55
  def title
    params[:title].presence
  end

56
57
58
59
60
61
62
63
64
65
66
67
  def project
    return @project if defined?(@project)

    if project_id
      @project = available_projects.find(project_id) rescue nil
    else
      @project = nil
    end

    @project
  end

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
68
69
70
  def projects
    return @projects if defined?(@projects)

71
72
73
    @projects = available_projects
    @projects = @projects.in_namespace(group_id) if group_id
    @projects = @projects.where(id: project_ids) if project_ids
74
    @projects = @projects.reorder(nil)
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
75
76
77

    @projects
  end
78
79
80
81

  def available_projects
    @available_projects ||= ProjectsFinder.new.execute(current_user)
  end
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
82
end