Class: SnippetsFinder

Inherits:
UnionFinder show all
Includes:
CreatedAtFilter, FinderMethods, Gitlab::Utils::StrongMemoize
Defined in:
app/finders/snippets_finder.rb

Overview

Finder for retrieving snippets that a user can see, optionally scoped to a project or snippets author.

Basic usage:

user = User.find(1)

SnippetsFinder.new(user).execute

To limit the snippets to a specific project, supply the ‘project:` option:

user = User.find(1)
project = Project.find(1)

SnippetsFinder.new(user, project: project).execute

Limiting snippets to an author can be done by supplying the ‘author:` option:

user = User.find(1)
project = Project.find(1)

SnippetsFinder.new(user, author: user).execute

To filter snippets using a specific visibility level, you can provide the ‘scope:` option:

user = User.find(1)
project = Project.find(1)

SnippetsFinder.new(user, author: user, scope: :are_public).execute

Valid ‘scope:` values are:

  • ‘:are_private`

  • ‘:are_internal`

  • ‘:are_public`

Any other value will be ignored.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from CreatedAtFilter

#by_created_at

Methods included from FinderMethods

#find, #find_by, #find_by!

Methods inherited from UnionFinder

#find_union

Constructor Details

#initialize(current_user = nil, params = {}) ⇒ SnippetsFinder

Returns a new instance of SnippetsFinder.



48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/finders/snippets_finder.rb', line 48

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

  if project && author
    raise(
      ArgumentError,
      'Filtering by both an author and a project is not supported, ' \
        'as this finder is not optimised for this use case'
    )
  end
end

Instance Attribute Details

#current_userObject (readonly)

Returns the value of attribute current_user.



46
47
48
# File 'app/finders/snippets_finder.rb', line 46

def current_user
  @current_user
end

#paramsObject (readonly)

Returns the value of attribute params.



46
47
48
# File 'app/finders/snippets_finder.rb', line 46

def params
  @params
end

Instance Method Details

#executeObject



61
62
63
64
65
66
67
68
69
70
71
# File 'app/finders/snippets_finder.rb', line 61

def execute
  # The snippet query can be expensive, therefore if the
  # author or project params have been passed and they don't
  # exist, or if a Project has been passed and has snippets
  # disabled, it's better to return
  return Snippet.none if author.nil? && params[:author].present?
  return Snippet.none if project.nil? && params[:project].present?
  return Snippet.none if project && !project.feature_available?(:snippets, current_user)

  filter_snippets.order_by(sort_param)
end