BigW Consortium Gitlab

snippets_finder.rb 1.51 KB
Newer Older
1 2 3
class SnippetsFinder
  def execute(current_user, params = {})
    filter = params[:filter]
4
    user = params.fetch(:user, current_user)
5 6 7

    case filter
    when :all then
8
      snippets(current_user).fresh
9 10
    when :public then
      Snippet.are_public.fresh
11
    when :by_user then
12
      by_user(current_user, user, params[:scope])
13
    when :by_project
14
      by_project(current_user, params[:project], params[:scope])
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
    end
  end

  private

  def snippets(current_user)
    if current_user
      Snippet.public_and_internal
    else
      # Not authenticated
      #
      # Return only:
      #   public snippets
      Snippet.are_public
    end
  end

  def by_user(current_user, user, scope)
33
    snippets = user.snippets.fresh
34

35 36 37
    if current_user
      include_private = user == current_user
      by_scope(snippets, scope, include_private)
38
    else
39
      snippets.are_public
40 41 42
    end
  end

43
  def by_project(current_user, project, scope)
44
    snippets = project.snippets.fresh
45 46

    if current_user
47 48
      include_private = project.team.member?(current_user) || current_user.admin?
      by_scope(snippets, scope, include_private)
49 50 51 52
    else
      snippets.are_public
    end
  end
53 54 55 56

  def by_scope(snippets, scope = nil, include_private = false)
    case scope.to_s
    when 'are_private'
57
      include_private ? snippets.are_private : Snippet.none
58 59 60 61 62 63 64 65
    when 'are_internal'
      snippets.are_internal
    when 'are_public'
      snippets.are_public
    else
      include_private ? snippets : snippets.public_and_internal
    end
  end
66
end