license_template_finder.rb 1.31 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7
# LicenseTemplateFinder
#
# Used to find license templates, which may come from a variety of external
# sources
#
8
# Params can be any of the following:
9 10 11
#   popular: boolean. When set to true, only "popular" licenses are shown. When
#            false, all licenses except popular ones are shown. When nil (the
#            default), *all* licenses will be shown.
12
#   name:    string. If set, return a single license matching that name (or nil)
13
class LicenseTemplateFinder
14
  include Gitlab::Utils::StrongMemoize
15

16 17 18 19
  attr_reader :project, :params

  def initialize(project, params = {})
    @project = project
20 21 22 23
    @params = params
  end

  def execute
24 25 26 27
    if params[:name]
      vendored_licenses.find { |template| template.key == params[:name] }
    else
      vendored_licenses
28 29 30 31 32
    end
  end

  private

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
  def vendored_licenses
    strong_memoize(:vendored_licenses) do
      Licensee::License.all(featured: popular_only?).map do |license|
        LicenseTemplate.new(
          key: license.key,
          name: license.name,
          nickname: license.nickname,
          category: (license.featured? ? :Popular : :Other),
          content: license.content,
          url: license.url,
          meta: license.meta
        )
      end
    end
  end

49 50 51 52
  def popular_only?
    params.fetch(:popular, nil)
  end
end