BigW Consortium Gitlab

snippets_finder.rb 1.46 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class SnippetsFinder < UnionFinder
  attr_accessor :current_user, :params

  def initialize(current_user, params = {})
    @current_user = current_user
    @params = params
  end

  def execute
    items = init_collection
    items = by_project(items)
    items = by_author(items)
    items = by_visibility(items)

    items.fresh
16 17 18 19
  end

  private

20 21 22 23
  def init_collection
    items = Snippet.all

    accessible(items)
24 25
  end

26 27 28 29
  def accessible(items)
    segments = []
    segments << items.public_to_user(current_user)
    segments << authorized_to_user(items)  if current_user
30

31
    find_union(segments, Snippet)
32 33
  end

34 35 36 37 38 39 40
  def authorized_to_user(items)
    items.where(
      'author_id = :author_id
       OR project_id IN (:project_ids)',
       author_id: current_user.id,
       project_ids: current_user.authorized_projects.select(:id))
  end
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  def by_visibility(items)
    visibility = params[:visibility] || visibility_from_scope

    return items unless visibility

    items.where(visibility_level: visibility)
  end

  def by_author(items)
    return items unless params[:author]

    items.where(author_id: params[:author].id)
  end

  def by_project(items)
    return items unless params[:project]

    items.where(project_id: params[:project].id)
60
  end
61

62 63
  def visibility_from_scope
    case params[:scope].to_s
64
    when 'are_private'
65
      Snippet::PRIVATE
66
    when 'are_internal'
67
      Snippet::INTERNAL
68
    when 'are_public'
69
      Snippet::PUBLIC
70
    else
71
      nil
72 73
    end
  end
74
end