debian-mirror-gitlab/app/services/labels/find_or_create_service.rb

58 lines
1.6 KiB
Ruby
Raw Normal View History

2016-11-03 12:29:30 +05:30
module Labels
class FindOrCreateService
2018-03-27 19:54:05 +05:30
def initialize(current_user, parent, params = {})
2016-11-03 12:29:30 +05:30
@current_user = current_user
2018-03-27 19:54:05 +05:30
@parent = parent
@available_labels = params.delete(:available_labels)
2017-08-17 22:00:37 +05:30
@params = params.dup.with_indifferent_access
2016-11-03 12:29:30 +05:30
end
def execute(skip_authorization: false)
@skip_authorization = skip_authorization
find_or_create_label
end
private
2018-03-27 19:54:05 +05:30
attr_reader :current_user, :parent, :params, :skip_authorization
2016-11-03 12:29:30 +05:30
def available_labels
@available_labels ||= LabelsFinder.new(
current_user,
2018-03-27 19:54:05 +05:30
"#{parent_type}_id".to_sym => parent.id,
2018-11-08 19:23:39 +05:30
include_ancestor_groups: include_ancestor_groups?,
2018-03-27 19:54:05 +05:30
only_group_labels: parent_is_group?
2016-11-03 12:29:30 +05:30
).execute(skip_authorization: skip_authorization)
end
2017-01-15 13:20:01 +05:30
# Only creates the label if current_user can do so, if the label does not exist
# and the user can not create the label, nil is returned
2016-11-03 12:29:30 +05:30
def find_or_create_label
new_label = available_labels.find_by(title: title)
2017-01-15 13:20:01 +05:30
2018-03-27 19:54:05 +05:30
if new_label.nil? && (skip_authorization || Ability.allowed?(current_user, :admin_label, parent))
2018-11-08 19:23:39 +05:30
create_params = params.except(:include_ancestor_groups)
new_label = Labels::CreateService.new(create_params).execute(parent_type.to_sym => parent)
2017-01-15 13:20:01 +05:30
end
2016-11-03 12:29:30 +05:30
new_label
end
def title
params[:title] || params[:name]
end
2018-03-27 19:54:05 +05:30
def parent_type
parent.model_name.param_key
end
def parent_is_group?
parent_type == "group"
end
2018-11-08 19:23:39 +05:30
def include_ancestor_groups?
params[:include_ancestor_groups] == true
end
2016-11-03 12:29:30 +05:30
end
end