summaryrefslogtreecommitdiff
path: root/app/models/snippet_input_action.rb
diff options
context:
space:
mode:
authorGitLab Bot <gitlab-bot@gitlab.com>2020-06-18 11:18:50 +0000
committerGitLab Bot <gitlab-bot@gitlab.com>2020-06-18 11:18:50 +0000
commit8c7f4e9d5f36cff46365a7f8c4b9c21578c1e781 (patch)
treea77e7fe7a93de11213032ed4ab1f33a3db51b738 /app/models/snippet_input_action.rb
parent00b35af3db1abfe813a778f643dad221aad51fca (diff)
downloadgitlab-ce-8c7f4e9d5f36cff46365a7f8c4b9c21578c1e781.tar.gz
Add latest changes from gitlab-org/gitlab@13-1-stable-ee
Diffstat (limited to 'app/models/snippet_input_action.rb')
-rw-r--r--app/models/snippet_input_action.rb62
1 files changed, 62 insertions, 0 deletions
diff --git a/app/models/snippet_input_action.rb b/app/models/snippet_input_action.rb
new file mode 100644
index 00000000000..7f4ab775ab0
--- /dev/null
+++ b/app/models/snippet_input_action.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+class SnippetInputAction
+ include ActiveModel::Validations
+
+ ACTIONS = %i[create update delete move].freeze
+
+ ACTIONS.each do |action_const|
+ define_method "#{action_const}_action?" do
+ action == action_const
+ end
+ end
+
+ attr_reader :action, :previous_path, :file_path, :content
+
+ validates :action, inclusion: { in: ACTIONS, message: "%{value} is not a valid action" }
+ validates :previous_path, presence: true, if: :move_action?
+ validates :file_path, presence: true
+ validates :content, presence: true, if: -> (action) { action.create_action? || action.update_action? }
+ validate :ensure_same_file_path_and_previous_path, if: :update_action?
+ validate :ensure_allowed_action
+
+ def initialize(action: nil, previous_path: nil, file_path: nil, content: nil, allowed_actions: nil)
+ @action = action&.to_sym
+ @previous_path = previous_path
+ @file_path = file_path
+ @content = content
+ @allowed_actions = Array(allowed_actions).map(&:to_sym)
+ end
+
+ def to_commit_action
+ {
+ action: action,
+ previous_path: build_previous_path,
+ file_path: file_path,
+ content: content
+ }
+ end
+
+ private
+
+ def build_previous_path
+ return previous_path unless update_action?
+
+ previous_path.presence || file_path
+ end
+
+ def ensure_same_file_path_and_previous_path
+ return if previous_path.blank? || file_path.blank?
+ return if previous_path == file_path
+
+ errors.add(:file_path, "can't be different from the previous_path attribute")
+ end
+
+ def ensure_allowed_action
+ return if @allowed_actions.empty?
+
+ unless @allowed_actions.include?(action)
+ errors.add(:action, 'is not allowed')
+ end
+ end
+end