diff options
author | Toon Claes <toon@gitlab.com> | 2019-02-28 19:57:34 +0100 |
---|---|---|
committer | Toon Claes <toon@gitlab.com> | 2019-02-28 19:57:34 +0100 |
commit | 62d7990b9bb30cf33ed87017c5c633d1cccc75c2 (patch) | |
tree | c3e1b69c58a412ba1c6f50a0337a23d9f9d6e1a4 /app/models/concerns | |
parent | f6453eca992a9c142268e78ac782cef98110d183 (diff) | |
download | gitlab-ce-tc-standard-gem.tar.gz |
Ran standardrb --fix on the whole codebasetc-standard-gem
Inspired by https://twitter.com/searls/status/1101137953743613952 I
decided to try https://github.com/testdouble/standard on our codebase.
It's opinionated, but at least it's a _standard_.
Diffstat (limited to 'app/models/concerns')
60 files changed, 347 insertions, 345 deletions
diff --git a/app/models/concerns/atomic_internal_id.rb b/app/models/concerns/atomic_internal_id.rb index 4e15b60ccd1..1e26abd947a 100644 --- a/app/models/concerns/atomic_internal_id.rb +++ b/app/models/concerns/atomic_internal_id.rb @@ -41,7 +41,7 @@ module AtomicInternalId return value unless scope_value - scope_attrs = { scope_value.class.table_name.singularize.to_sym => scope_value } + scope_attrs = {scope_value.class.table_name.singularize.to_sym => scope_value} usage = self.class.table_name.to_sym if value.present? diff --git a/app/models/concerns/avatarable.rb b/app/models/concerns/avatarable.rb index 4687ec7d166..0be3fa992fd 100644 --- a/app/models/concerns/avatarable.rb +++ b/app/models/concerns/avatarable.rb @@ -9,7 +9,7 @@ module Avatarable include Gitlab::Utils::StrongMemoize validate :avatar_type, if: ->(user) { user.avatar.present? && user.avatar_changed? } - validates :avatar, file_size: { maximum: 200.kilobytes.to_i }, if: :avatar_changed? + validates :avatar, file_size: {maximum: 200.kilobytes.to_i}, if: :avatar_changed? mount_uploader :avatar, AvatarUploader @@ -37,24 +37,24 @@ module Avatarable end def avatar_type - unless self.avatar.image? - errors.add :avatar, "file format is not supported. Please try one of the following supported formats: #{AvatarUploader::IMAGE_EXT.join(', ')}" + unless avatar.image? + errors.add :avatar, "file format is not supported. Please try one of the following supported formats: #{AvatarUploader::IMAGE_EXT.join(", ")}" end end def avatar_path(only_path: true, size: nil) - unless self.try(:id) + unless try(:id) return uncached_avatar_path(only_path: only_path, size: size) end # Cache this avatar path only within the request because avatars in # object storage may be generated with time-limited, signed URLs. - key = "#{self.class.name}:#{self.id}:#{only_path}:#{size}" + key = "#{self.class.name}:#{id}:#{only_path}:#{size}" Gitlab::SafeRequestStore[key] ||= uncached_avatar_path(only_path: only_path, size: size) end def uncached_avatar_path(only_path: true, size: nil) - return unless self.try(:avatar).present? + return unless try(:avatar).present? asset_host = ActionController::Base.asset_host use_asset_host = asset_host.present? @@ -93,14 +93,14 @@ module Avatarable def retrieve_upload_from_batch(identifier) BatchLoader.for(identifier: identifier, model: self).batch(key: self.class) do |upload_params, loader, args| model_class = args[:key] - paths = upload_params.flat_map do |params| + paths = upload_params.flat_map { |params| params[:model].upload_paths(params[:identifier]) - end + } Upload.where(uploader: AvatarUploader.name, path: paths).find_each do |upload| - model = model_class.instantiate('id' => upload.model_id) + model = model_class.instantiate("id" => upload.model_id) - loader.call({ model: model, identifier: File.basename(upload.path) }, upload) + loader.call({model: model, identifier: File.basename(upload.path)}, upload) end end end diff --git a/app/models/concerns/awardable.rb b/app/models/concerns/awardable.rb index 14bc56f0eee..96092fcfbd1 100644 --- a/app/models/concerns/awardable.rb +++ b/app/models/concerns/awardable.rb @@ -21,7 +21,7 @@ module Awardable WHERE user_id = :user_id AND #{"name = :name AND" if name.present?} awardable_type = :awardable_type AND - awardable_id = #{self.arel_table.name}.id + awardable_id = #{arel_table.name}.id ) EOL @@ -35,33 +35,33 @@ module Awardable FROM award_emoji WHERE user_id = :user_id AND awardable_type = :awardable_type AND - awardable_id = #{self.arel_table.name}.id + awardable_id = #{arel_table.name}.id ) EOL - where(sql, user_id: user.id, awardable_type: self.name) + where(sql, user_id: user.id, awardable_type: name) end def order_upvotes_desc - order_votes(AwardEmoji::UPVOTE_NAME, 'DESC') + order_votes(AwardEmoji::UPVOTE_NAME, "DESC") end def order_upvotes_asc - order_votes(AwardEmoji::UPVOTE_NAME, 'ASC') + order_votes(AwardEmoji::UPVOTE_NAME, "ASC") end def order_downvotes_desc - order_votes(AwardEmoji::DOWNVOTE_NAME, 'DESC') + order_votes(AwardEmoji::DOWNVOTE_NAME, "DESC") end # Order votes by emoji, optional sort order param `descending` defaults to true def order_votes(emoji_name, direction) - awardable_table = self.arel_table + awardable_table = arel_table awards_table = AwardEmoji.arel_table join_clause = awardable_table.join(awards_table, Arel::Nodes::OuterJoin).on( awards_table[:awardable_id].eq(awardable_table[:id]).and( - awards_table[:awardable_type].eq(self.name).and( + awards_table[:awardable_type].eq(name).and( awards_table[:name].eq(emoji_name) ) ) @@ -100,7 +100,7 @@ module Awardable end def user_authored?(current_user) - author = self.respond_to?(:author) ? self.author : self.user + author = respond_to?(:author) ? self.author : user author == current_user end diff --git a/app/models/concerns/blob_language_from_git_attributes.rb b/app/models/concerns/blob_language_from_git_attributes.rb index 70213d22147..45ff64d83de 100644 --- a/app/models/concerns/blob_language_from_git_attributes.rb +++ b/app/models/concerns/blob_language_from_git_attributes.rb @@ -8,6 +8,6 @@ module BlobLanguageFromGitAttributes return nil unless project repository = project.repository - repository.gitattribute(path, 'gitlab-language') + repository.gitattribute(path, "gitlab-language") end end diff --git a/app/models/concerns/blocks_json_serialization.rb b/app/models/concerns/blocks_json_serialization.rb index 18c00532d78..5cbfd5e11d7 100644 --- a/app/models/concerns/blocks_json_serialization.rb +++ b/app/models/concerns/blocks_json_serialization.rb @@ -14,5 +14,5 @@ module BlocksJsonSerialization "JSON serialization has been disabled on #{self.class.name}" end - alias_method :as_json, :to_json + alias as_json to_json end diff --git a/app/models/concerns/bulk_member_access_load.rb b/app/models/concerns/bulk_member_access_load.rb index 041ed3755e0..384adefa838 100644 --- a/app/models/concerns/bulk_member_access_load.rb +++ b/app/models/concerns/bulk_member_access_load.rb @@ -9,8 +9,8 @@ module BulkMemberAccessLoad # Determine the maximum access level for a group of resources in bulk. # # Returns a Hash mapping resource ID -> maximum access level. - def max_member_access_for_resource_ids(resource_klass, resource_ids, memoization_index = self.id, &block) - raise 'Block is mandatory' unless block_given? + def max_member_access_for_resource_ids(resource_klass, resource_ids, memoization_index = id, &block) + raise "Block is mandatory" unless block_given? resource_ids = resource_ids.uniq key = max_member_access_for_resource_key(resource_klass, memoization_index) @@ -22,7 +22,7 @@ module BulkMemberAccessLoad end # Look up only the IDs we need - resource_ids = resource_ids - access.keys + resource_ids -= access.keys return access if resource_ids.empty? diff --git a/app/models/concerns/cache_markdown_field.rb b/app/models/concerns/cache_markdown_field.rb index 1a8570b80c3..191bd418c2e 100644 --- a/app/models/concerns/cache_markdown_field.rb +++ b/app/models/concerns/cache_markdown_field.rb @@ -51,12 +51,12 @@ module CacheMarkdownField cached_markdown_fields.markdown_fields.include?(field) # Always include a project key, or Banzai complains - project = self.project if self.respond_to?(:project) - group = self.group if self.respond_to?(:group) + project = self.project if respond_to?(:project) + group = self.group if respond_to?(:group) context = cached_markdown_fields[field].merge(project: project, group: group) # Banzai is less strict about authors, so don't always have an author key - context[:author] = self.author if self.respond_to?(:author) + context[:author] = author if respond_to?(:author) context[:markdown_engine] = :common_mark @@ -66,15 +66,15 @@ module CacheMarkdownField # Update every column in a row if any one is invalidated, as we only store # one version per row def refresh_markdown_cache - options = { skip_project_check: skip_project_check? } + options = {skip_project_check: skip_project_check?} - updates = cached_markdown_fields.markdown_fields.map do |markdown_field| + updates = cached_markdown_fields.markdown_fields.map { |markdown_field| [ cached_markdown_fields.html_field(markdown_field), - Banzai::Renderer.cacheless_render_field(self, markdown_field, options) + Banzai::Renderer.cacheless_render_field(self, markdown_field, options), ] - end.to_h - updates['cached_markdown_version'] = latest_cached_markdown_version + }.to_h + updates["cached_markdown_version"] = latest_cached_markdown_version updates.each {|html_field, data| write_attribute(html_field, data) } end @@ -150,7 +150,7 @@ module CacheMarkdownField def attributes attrs = attributes_before_markdown_cache - attrs.delete('cached_markdown_version') + attrs.delete("cached_markdown_version") cached_markdown_fields.html_fields.each do |field| attrs.delete(field) diff --git a/app/models/concerns/cacheable_attributes.rb b/app/models/concerns/cacheable_attributes.rb index 3d60f6924c1..ffba6e8fb92 100644 --- a/app/models/concerns/cacheable_attributes.rb +++ b/app/models/concerns/cacheable_attributes.rb @@ -9,7 +9,7 @@ module CacheableAttributes class_methods do def cache_key - "#{name}:#{Gitlab::VERSION}:#{Rails.version}".freeze + "#{name}:#{Gitlab::VERSION}:#{Rails.version}" end # Can be overridden diff --git a/app/models/concerns/case_sensitivity.rb b/app/models/concerns/case_sensitivity.rb index c93b6589ee7..325ddc58bf0 100644 --- a/app/models/concerns/case_sensitivity.rb +++ b/app/models/concerns/case_sensitivity.rb @@ -17,7 +17,7 @@ module CaseSensitivity criteria.where(value_in(key, value)) else criteria.where(value_equal(key, value)) - end + end end criteria @@ -32,9 +32,9 @@ module CaseSensitivity end def value_in(column, values) - lower_values = values.map do |value| + lower_values = values.map { |value| lower_value(value) - end + } lower_column(arel_table[column]).in(lower_values).to_sql end @@ -42,7 +42,7 @@ module CaseSensitivity def lower_value(value) return value if Gitlab::Database.mysql? - Arel::Nodes::NamedFunction.new('LOWER', [Arel::Nodes.build_quoted(value)]) + Arel::Nodes::NamedFunction.new("LOWER", [Arel::Nodes.build_quoted(value)]) end def lower_column(column) diff --git a/app/models/concerns/chronic_duration_attribute.rb b/app/models/concerns/chronic_duration_attribute.rb index af4905115b1..e4fd20bc654 100644 --- a/app/models/concerns/chronic_duration_attribute.rb +++ b/app/models/concerns/chronic_duration_attribute.rb @@ -24,7 +24,7 @@ module ChronicDurationAttribute end end - validates virtual_attribute, allow_nil: true, duration: { message: parameters[:error_message] } + validates virtual_attribute, allow_nil: true, duration: {message: parameters[:error_message]} end alias_method :chronic_duration_attr, :chronic_duration_attr_writer diff --git a/app/models/concerns/ci/metadatable.rb b/app/models/concerns/ci/metadatable.rb index 9eed9492b37..cb1a8ce423d 100644 --- a/app/models/concerns/ci/metadatable.rb +++ b/app/models/concerns/ci/metadatable.rb @@ -9,7 +9,7 @@ module Ci extend ActiveSupport::Concern included do - has_one :metadata, class_name: 'Ci::BuildMetadata', + has_one :metadata, class_name: "Ci::BuildMetadata", foreign_key: :build_id, inverse_of: :build, autosave: true @@ -23,13 +23,13 @@ module Ci end def degenerated? - self.options.blank? + options.blank? end def degenerate! self.class.transaction do - self.update!(options: nil, yaml_variables: nil) - self.metadata&.destroy + update!(options: nil, yaml_variables: nil) + metadata&.destroy end end diff --git a/app/models/concerns/ci/processable.rb b/app/models/concerns/ci/processable.rb index 1c78b1413a8..f84f9f12dfe 100644 --- a/app/models/concerns/ci/processable.rb +++ b/app/models/concerns/ci/processable.rb @@ -17,7 +17,7 @@ module Ci end def when - read_attribute(:when) || 'on_success' + read_attribute(:when) || "on_success" end def expanded_environment_name diff --git a/app/models/concerns/deployable.rb b/app/models/concerns/deployable.rb index bc12b06b5af..6330de41e5b 100644 --- a/app/models/concerns/deployable.rb +++ b/app/models/concerns/deployable.rb @@ -24,7 +24,8 @@ module Deployable tag: tag, sha: sha, user: user, - on_stop: on_stop) + on_stop: on_stop + ) end end end diff --git a/app/models/concerns/deployment_platform.rb b/app/models/concerns/deployment_platform.rb index 0107af5f8ec..5d86a7fbb27 100644 --- a/app/models/concerns/deployment_platform.rb +++ b/app/models/concerns/deployment_platform.rb @@ -53,12 +53,12 @@ module DeploymentPlatform def cluster_attributes_from_service_template { - name: 'kubernetes-template', + name: "kubernetes-template", projects: [self], cluster_type: :project_type, provider_type: :user, platform_type: :kubernetes, - platform_kubernetes_attributes: platform_kubernetes_attributes_from_service_template + platform_kubernetes_attributes: platform_kubernetes_attributes_from_service_template, } end @@ -67,7 +67,7 @@ module DeploymentPlatform api_url: kubernetes_service_template.api_url, ca_pem: kubernetes_service_template.ca_pem, token: kubernetes_service_template.token, - namespace: kubernetes_service_template.namespace + namespace: kubernetes_service_template.namespace, } end end diff --git a/app/models/concerns/diff_positionable_note.rb b/app/models/concerns/diff_positionable_note.rb index b61bf29e6ad..1cae121b024 100644 --- a/app/models/concerns/diff_positionable_note.rb +++ b/app/models/concerns/diff_positionable_note.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + module DiffPositionableNote extend ActiveSupport::Concern @@ -11,10 +12,14 @@ module DiffPositionableNote serialize :change_position, Gitlab::Diff::Position # rubocop:disable Cop/ActiveRecordSerialize end - %i(original_position position change_position).each do |meth| + %i[original_position position change_position].each do |meth| define_method "#{meth}=" do |new_position| if new_position.is_a?(String) - new_position = JSON.parse(new_position) rescue nil + new_position = begin + JSON.parse(new_position) + rescue + nil + end end if new_position.is_a?(Hash) @@ -37,7 +42,7 @@ module DiffPositionableNote end def supported? - for_commit? || self.noteable.has_complete_diff_refs? + for_commit? || noteable.has_complete_diff_refs? end def active?(diff_refs = nil) @@ -46,13 +51,13 @@ module DiffPositionableNote diff_refs ||= noteable.diff_refs - self.position.diff_refs == diff_refs + position.diff_refs == diff_refs end def set_original_position return unless position - self.original_position = self.position.dup unless self.original_position&.complete? + self.original_position = position.dup unless original_position&.complete? end def update_position @@ -63,13 +68,13 @@ module DiffPositionableNote return unless position tracer = Gitlab::Diff::PositionTracer.new( - project: self.project, - old_diff_refs: self.position.diff_refs, - new_diff_refs: self.noteable.diff_refs, - paths: self.position.paths + project: project, + old_diff_refs: position.diff_refs, + new_diff_refs: noteable.diff_refs, + paths: position.paths ) - result = tracer.trace(self.position) + result = tracer.trace(position) return unless result if result[:outdated] diff --git a/app/models/concerns/discussion_on_diff.rb b/app/models/concerns/discussion_on_diff.rb index e4e5928f5cf..74488919b62 100644 --- a/app/models/concerns/discussion_on_diff.rb +++ b/app/models/concerns/discussion_on_diff.rb @@ -8,21 +8,19 @@ module DiscussionOnDiff included do delegate :line_code, - :original_line_code, - :note_diff_file, - :diff_line, - :active?, - :created_at_diff?, - - to: :first_note + :original_line_code, + :note_diff_file, + :diff_line, + :active?, + :created_at_diff?, + to: :first_note delegate :file_path, - :blob, - :highlighted_diff_lines, - :diff_lines, - - to: :diff_file, - allow_nil: true + :blob, + :highlighted_diff_lines, + :diff_lines, + to: :diff_file, + allow_nil: true end def diff_discussion? @@ -79,8 +77,7 @@ module DiscussionOnDiff def fetch_preloaded_diff_file fetch_preloaded_diff = - context_noteable && - context_noteable.preloads_discussion_diff_highlighting? && + context_noteable&.preloads_discussion_diff_highlighting? && note_diff_file context_noteable.discussions_diffs.find_by_id(note_diff_file.id) if fetch_preloaded_diff diff --git a/app/models/concerns/each_batch.rb b/app/models/concerns/each_batch.rb index 6314b46a7e3..3472c9dea9b 100644 --- a/app/models/concerns/each_batch.rb +++ b/app/models/concerns/each_batch.rb @@ -50,7 +50,7 @@ module EachBatch def each_batch(of: 1000, column: primary_key, order_hint: nil) unless column raise ArgumentError, - 'the column: argument must be set to a column name to use for ordering rows' + "the column: argument must be set to a column name to use for ordering rows" end start = except(:select) diff --git a/app/models/concerns/expirable.rb b/app/models/concerns/expirable.rb index 1f274487935..592f9d8fabf 100644 --- a/app/models/concerns/expirable.rb +++ b/app/models/concerns/expirable.rb @@ -4,7 +4,7 @@ module Expirable extend ActiveSupport::Concern included do - scope :expired, -> { where('expires_at <= ?', Time.current) } + scope :expired, -> { where("expires_at <= ?", Time.current) } end def expired? diff --git a/app/models/concerns/fast_destroy_all.rb b/app/models/concerns/fast_destroy_all.rb index f862031bce0..e641c1237aa 100644 --- a/app/models/concerns/fast_destroy_all.rb +++ b/app/models/concerns/fast_destroy_all.rb @@ -34,7 +34,7 @@ module FastDestroyAll included do before_destroy do - raise ForbiddenActionError, '`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`' + raise ForbiddenActionError, "`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`" end end diff --git a/app/models/concerns/ghost_user.rb b/app/models/concerns/ghost_user.rb index 15278c431fb..e7255ae710a 100644 --- a/app/models/concerns/ghost_user.rb +++ b/app/models/concerns/ghost_user.rb @@ -4,6 +4,6 @@ module GhostUser extend ActiveSupport::Concern def ghost_user? - user && user.ghost? + user&.ghost? end end diff --git a/app/models/concerns/group_descendant.rb b/app/models/concerns/group_descendant.rb index 05cd4265133..68ab20f1371 100644 --- a/app/models/concerns/group_descendant.rb +++ b/app/models/concerns/group_descendant.rb @@ -22,12 +22,12 @@ module GroupDescendant return [] if descendants.empty? unless descendants.all? { |hierarchy| hierarchy.is_a?(GroupDescendant) } - raise ArgumentError.new('element is not a hierarchy') + raise ArgumentError.new("element is not a hierarchy") end - all_hierarchies = descendants.map do |descendant| + all_hierarchies = descendants.map { |descendant| descendant.hierarchy(hierarchy_top, descendants) - end + } Gitlab::Utils::MergeHash.merge(all_hierarchies) end @@ -48,22 +48,22 @@ module GroupDescendant extras = { parent: parent.inspect, child: child.inspect, - preloaded: preloaded.map(&:full_path) + preloaded: preloaded.map(&:full_path), } - issue_url = 'https://gitlab.com/gitlab-org/gitlab-ce/issues/40785' + issue_url = "https://gitlab.com/gitlab-org/gitlab-ce/issues/40785" Gitlab::Sentry.track_exception(exception, issue_url: issue_url, extra: extras) end if parent.nil? && hierarchy_top.present? - raise ArgumentError.new('specified top is not part of the tree') + raise ArgumentError.new("specified top is not part of the tree") end if parent && parent != hierarchy_top expand_hierarchy_for_child(parent, - { parent => hierarchy }, - hierarchy_top, - preloaded) + {parent => hierarchy}, + hierarchy_top, + preloaded) else hierarchy end diff --git a/app/models/concerns/has_status.rb b/app/models/concerns/has_status.rb index 0d2be4c61ab..c8436fe74f7 100644 --- a/app/models/concerns/has_status.rb +++ b/app/models/concerns/has_status.rb @@ -3,16 +3,16 @@ module HasStatus extend ActiveSupport::Concern - DEFAULT_STATUS = 'created'.freeze + DEFAULT_STATUS = "created" BLOCKED_STATUS = %w[manual scheduled].freeze AVAILABLE_STATUSES = %w[created pending running success failed canceled skipped manual scheduled].freeze STARTED_STATUSES = %w[running success failed skipped manual scheduled].freeze ACTIVE_STATUSES = %w[pending running].freeze COMPLETED_STATUSES = %w[success failed canceled skipped].freeze ORDERED_STATUSES = %w[failed pending running manual scheduled canceled success skipped created].freeze - STATUSES_ENUM = { created: 0, pending: 1, running: 2, success: 3, - failed: 4, canceled: 5, skipped: 6, manual: 7, - scheduled: 8 }.freeze + STATUSES_ENUM = {created: 0, pending: 1, running: 2, success: 3, + failed: 4, canceled: 5, skipped: 6, manual: 7, + scheduled: 8,}.freeze UnknownStatusError = Class.new(StandardError) @@ -21,16 +21,16 @@ module HasStatus scope_relevant = respond_to?(:exclude_ignored) ? exclude_ignored : all scope_warnings = respond_to?(:failed_but_allowed) ? failed_but_allowed : none - builds = scope_relevant.select('count(*)').to_sql - created = scope_relevant.created.select('count(*)').to_sql - success = scope_relevant.success.select('count(*)').to_sql - manual = scope_relevant.manual.select('count(*)').to_sql - scheduled = scope_relevant.scheduled.select('count(*)').to_sql - pending = scope_relevant.pending.select('count(*)').to_sql - running = scope_relevant.running.select('count(*)').to_sql - skipped = scope_relevant.skipped.select('count(*)').to_sql - canceled = scope_relevant.canceled.select('count(*)').to_sql - warnings = scope_warnings.select('count(*) > 0').to_sql.presence || 'false' + builds = scope_relevant.select("count(*)").to_sql + created = scope_relevant.created.select("count(*)").to_sql + success = scope_relevant.success.select("count(*)").to_sql + manual = scope_relevant.manual.select("count(*)").to_sql + scheduled = scope_relevant.scheduled.select("count(*)").to_sql + pending = scope_relevant.pending.select("count(*)").to_sql + running = scope_relevant.running.select("count(*)").to_sql + skipped = scope_relevant.skipped.select("count(*)").to_sql + canceled = scope_relevant.canceled.select("count(*)").to_sql + warnings = scope_warnings.select("count(*) > 0").to_sql.presence || "false" "(CASE WHEN (#{builds})=(#{skipped}) AND (#{warnings}) THEN 'success' @@ -66,30 +66,30 @@ module HasStatus end included do - validates :status, inclusion: { in: AVAILABLE_STATUSES } + validates :status, inclusion: {in: AVAILABLE_STATUSES} state_machine :status, initial: :created do - state :created, value: 'created' - state :pending, value: 'pending' - state :running, value: 'running' - state :failed, value: 'failed' - state :success, value: 'success' - state :canceled, value: 'canceled' - state :skipped, value: 'skipped' - state :manual, value: 'manual' - state :scheduled, value: 'scheduled' + state :created, value: "created" + state :pending, value: "pending" + state :running, value: "running" + state :failed, value: "failed" + state :success, value: "success" + state :canceled, value: "canceled" + state :skipped, value: "skipped" + state :manual, value: "manual" + state :scheduled, value: "scheduled" end - scope :created, -> { where(status: 'created') } - scope :relevant, -> { where(status: AVAILABLE_STATUSES - ['created']) } - scope :running, -> { where(status: 'running') } - scope :pending, -> { where(status: 'pending') } - scope :success, -> { where(status: 'success') } - scope :failed, -> { where(status: 'failed') } - scope :canceled, -> { where(status: 'canceled') } - scope :skipped, -> { where(status: 'skipped') } - scope :manual, -> { where(status: 'manual') } - scope :scheduled, -> { where(status: 'scheduled') } + scope :created, -> { where(status: "created") } + scope :relevant, -> { where(status: AVAILABLE_STATUSES - ["created"]) } + scope :running, -> { where(status: "running") } + scope :pending, -> { where(status: "pending") } + scope :success, -> { where(status: "success") } + scope :failed, -> { where(status: "failed") } + scope :canceled, -> { where(status: "canceled") } + scope :skipped, -> { where(status: "skipped") } + scope :manual, -> { where(status: "manual") } + scope :scheduled, -> { where(status: "scheduled") } scope :alive, -> { where(status: [:created, :pending, :running]) } scope :created_or_pending, -> { where(status: [:created, :pending]) } scope :running_or_pending, -> { where(status: [:running, :pending]) } diff --git a/app/models/concerns/has_variable.rb b/app/models/concerns/has_variable.rb index 2ec42a1029b..342b255347e 100644 --- a/app/models/concerns/has_variable.rb +++ b/app/models/concerns/has_variable.rb @@ -6,17 +6,17 @@ module HasVariable included do validates :key, presence: true, - length: { maximum: 255 }, - format: { with: /\A[a-zA-Z0-9_]+\z/, - message: "can contain only letters, digits and '_'." } + length: {maximum: 255}, + format: {with: /\A[a-zA-Z0-9_]+\z/, + message: "can contain only letters, digits and '_'.",} scope :order_key_asc, -> { reorder(key: :asc) } attr_encrypted :value, - mode: :per_attribute_iv_and_salt, - insecure_mode: true, - key: Settings.attr_encrypted_db_key_base, - algorithm: 'aes-256-cbc' + mode: :per_attribute_iv_and_salt, + insecure_mode: true, + key: Settings.attr_encrypted_db_key_base, + algorithm: "aes-256-cbc" def key=(new_key) super(new_key.to_s.strip) @@ -24,6 +24,6 @@ module HasVariable end def to_runner_variable - { key: key, value: value, public: false } + {key: key, value: value, public: false} end end diff --git a/app/models/concerns/importable.rb b/app/models/concerns/importable.rb index 4d2707b08ab..451bae34575 100644 --- a/app/models/concerns/importable.rb +++ b/app/models/concerns/importable.rb @@ -4,8 +4,8 @@ module Importable extend ActiveSupport::Concern attr_accessor :importing - alias_method :importing?, :importing + alias importing? importing attr_accessor :imported - alias_method :imported?, :imported + alias imported? imported end diff --git a/app/models/concerns/issuable.rb b/app/models/concerns/issuable.rb index 670103bc3f3..82264983cef 100644 --- a/app/models/concerns/issuable.rb +++ b/app/models/concerns/issuable.rb @@ -36,9 +36,9 @@ module Issuable redact_field :description - belongs_to :author, class_name: 'User' - belongs_to :updated_by, class_name: 'User' - belongs_to :last_edited_by, class_name: 'User' + belongs_to :author, class_name: "User" + belongs_to :updated_by, class_name: "User" + belongs_to :last_edited_by, class_name: "User" belongs_to :milestone has_many :notes, as: :noteable, inverse_of: :noteable, dependent: :destroy do # rubocop:disable Cop/ActiveRecordDependent @@ -60,42 +60,42 @@ module Issuable has_one :metrics delegate :name, - :email, - :public_email, - to: :author, - allow_nil: true, - prefix: true + :email, + :public_email, + to: :author, + allow_nil: true, + prefix: true delegate :name, - :email, - :public_email, - to: :assignee, - allow_nil: true, - prefix: true + :email, + :public_email, + to: :assignee, + allow_nil: true, + prefix: true validates :author, presence: true - validates :title, presence: true, length: { maximum: 255 } + validates :title, presence: true, length: {maximum: 255} scope :authored, ->(user) { where(author_id: user) } scope :recent, -> { reorder(id: :desc) } scope :of_projects, ->(ids) { where(project_id: ids) } scope :of_milestones, ->(ids) { where(milestone_id: ids) } - scope :any_milestone, -> { where('milestone_id IS NOT NULL') } - scope :with_milestone, ->(title) { left_joins_milestones.where(milestones: { title: title }) } + scope :any_milestone, -> { where("milestone_id IS NOT NULL") } + scope :with_milestone, ->(title) { left_joins_milestones.where(milestones: {title: title}) } scope :opened, -> { with_state(:opened) } scope :only_opened, -> { with_state(:opened) } scope :closed, -> { with_state(:closed) } scope :left_joins_milestones, -> { joins("LEFT OUTER JOIN milestones ON #{table_name}.milestone_id = milestones.id") } - scope :order_milestone_due_desc, -> { left_joins_milestones.reorder('milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date DESC') } - scope :order_milestone_due_asc, -> { left_joins_milestones.reorder('milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date ASC') } + scope :order_milestone_due_desc, -> { left_joins_milestones.reorder("milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date DESC") } + scope :order_milestone_due_asc, -> { left_joins_milestones.reorder("milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date ASC") } - scope :without_label, -> { joins("LEFT OUTER JOIN label_links ON label_links.target_type = '#{name}' AND label_links.target_id = #{table_name}.id").where(label_links: { id: nil }) } + scope :without_label, -> { joins("LEFT OUTER JOIN label_links ON label_links.target_type = '#{name}' AND label_links.target_id = #{table_name}.id").where(label_links: {id: nil}) } scope :any_label, -> { joins(:label_links).group(:id) } scope :join_project, -> { joins(:project) } scope :inc_notes_with_associations, -> { includes(notes: [:project, :author, :award_emoji]) } scope :references_project, -> { references(:project) } - scope :non_archived, -> { join_project.where(projects: { archived: false }) } + scope :non_archived, -> { join_project.where(projects: {archived: false}) } attr_mentionable :title, pipeline: :single_line attr_mentionable :description @@ -140,9 +140,9 @@ module Issuable # matched_columns - Modify the scope of the query. 'title', 'description' or joining them with a comma. # # Returns an ActiveRecord::Relation. - def full_search(query, matched_columns: 'title,description') + def full_search(query, matched_columns: "title,description") allowed_columns = [:title, :description] - matched_columns = matched_columns.to_s.split(',').map(&:to_sym) + matched_columns = matched_columns.to_s.split(",").map(&:to_sym) matched_columns &= allowed_columns # Matching title or description if the matched_columns did not contain any allowed columns. @@ -154,16 +154,16 @@ module Issuable def sort_by_attribute(method, excluded_labels: []) sorted = case method.to_s - when 'downvotes_desc' then order_downvotes_desc - when 'label_priority' then order_labels_priority(excluded_labels: excluded_labels) - when 'label_priority_desc' then order_labels_priority('DESC', excluded_labels: excluded_labels) - when 'milestone', 'milestone_due_asc' then order_milestone_due_asc - when 'milestone_due_desc' then order_milestone_due_desc - when 'popularity', 'popularity_desc' then order_upvotes_desc - when 'popularity_asc' then order_upvotes_asc - when 'priority', 'priority_asc' then order_due_date_and_labels_priority(excluded_labels: excluded_labels) - when 'priority_desc' then order_due_date_and_labels_priority('DESC', excluded_labels: excluded_labels) - when 'upvotes_desc' then order_upvotes_desc + when "downvotes_desc" then order_downvotes_desc + when "label_priority" then order_labels_priority(excluded_labels: excluded_labels) + when "label_priority_desc" then order_labels_priority("DESC", excluded_labels: excluded_labels) + when "milestone", "milestone_due_asc" then order_milestone_due_asc + when "milestone_due_desc" then order_milestone_due_desc + when "popularity", "popularity_desc" then order_upvotes_desc + when "popularity_asc" then order_upvotes_asc + when "priority", "priority_asc" then order_due_date_and_labels_priority(excluded_labels: excluded_labels) + when "priority_desc" then order_due_date_and_labels_priority("DESC", excluded_labels: excluded_labels) + when "upvotes_desc" then order_upvotes_desc else order_by(method) end @@ -171,7 +171,7 @@ module Issuable sorted.with_order_id_desc end - def order_due_date_and_labels_priority(direction = 'ASC', excluded_labels: []) + def order_due_date_and_labels_priority(direction = "ASC", excluded_labels: []) # The order_ methods also modify the query in other ways: # # - For milestones, we add a JOIN. @@ -184,39 +184,39 @@ module Issuable # 2. We can't ORDER BY a column that isn't in the GROUP BY and doesn't # have an aggregate function applied, so we do a useless MIN() instead. # - milestones_due_date = 'MIN(milestones.due_date)' + milestones_due_date = "MIN(milestones.due_date)" order_milestone_due_asc .order_labels_priority(excluded_labels: excluded_labels, extra_select_columns: [milestones_due_date]) .reorder(Gitlab::Database.nulls_last_order(milestones_due_date, direction), - Gitlab::Database.nulls_last_order('highest_priority', direction)) + Gitlab::Database.nulls_last_order("highest_priority", direction)) end - def order_labels_priority(direction = 'ASC', excluded_labels: [], extra_select_columns: []) + def order_labels_priority(direction = "ASC", excluded_labels: [], extra_select_columns: []) params = { target_type: name, target_column: "#{table_name}.id", project_column: "#{table_name}.#{project_foreign_key}", - excluded_labels: excluded_labels + excluded_labels: excluded_labels, } highest_priority = highest_label_priority(params).to_sql select_columns = [ "#{table_name}.*", - "(#{highest_priority}) AS highest_priority" + "(#{highest_priority}) AS highest_priority", ] + extra_select_columns - select(select_columns.join(', ')) + select(select_columns.join(", ")) .group(arel_table[:id]) - .reorder(Gitlab::Database.nulls_last_order('highest_priority', direction)) + .reorder(Gitlab::Database.nulls_last_order("highest_priority", direction)) end def with_label(title, sort = nil) if title.is_a?(Array) && title.size > 1 - joins(:labels).where(labels: { title: title }).group(*grouping_columns(sort)).having("COUNT(DISTINCT labels.title) = #{title.size}") + joins(:labels).where(labels: {title: title}).group(*grouping_columns(sort)).having("COUNT(DISTINCT labels.title) = #{title.size}") else - joins(:labels).where(labels: { title: title }) + joins(:labels).where(labels: {title: title}) end end @@ -227,7 +227,7 @@ module Issuable def grouping_columns(sort) grouping_columns = [arel_table[:id]] - if %w(milestone_due_desc milestone_due_asc milestone).include?(sort) + if %w[milestone_due_desc milestone_due_asc milestone].include?(sort) milestone_table = Milestone.arel_table grouping_columns << milestone_table[:id] grouping_columns << milestone_table[:due_date] @@ -289,14 +289,14 @@ module Issuable end if old_assignees != assignees - if self.is_a?(Issue) + if is_a?(Issue) changes[:assignees] = [old_assignees.map(&:hook_attrs), assignees.map(&:hook_attrs)] else changes[:assignee] = [old_assignees&.first&.hook_attrs, assignee&.hook_attrs] end end - if self.respond_to?(:total_time_spent) + if respond_to?(:total_time_spent) old_total_time_spent = old_associations.fetch(:total_time_spent, nil) if old_total_time_spent != total_time_spent @@ -313,7 +313,7 @@ module Issuable end def label_names - labels.order('title ASC').pluck(:title) + labels.order("title ASC").pluck(:title) end # Convert this Issuable class name to a format usable by Ability definitions @@ -329,8 +329,8 @@ module Issuable # Returns a Hash of attributes to be used for Twitter card metadata def card_attributes { - 'Author' => author.try(:name), - 'Assignee' => assignee.try(:name) + "Author" => author.try(:name), + "Assignee" => assignee.try(:name), } end @@ -353,7 +353,7 @@ module Issuable end def updated_tasks - Taskable.get_updated_tasks(old_content: previous_changes['description'].first, + Taskable.get_updated_tasks(old_content: previous_changes["description"].first, new_content: description) end @@ -374,7 +374,7 @@ module Issuable end def ensure_metrics - self.metrics || create_metrics + metrics || create_metrics end ## diff --git a/app/models/concerns/loaded_in_group_list.rb b/app/models/concerns/loaded_in_group_list.rb index fc15c6d55ed..143ff09b88d 100644 --- a/app/models/concerns/loaded_in_group_list.rb +++ b/app/models/concerns/loaded_in_group_list.rb @@ -6,10 +6,10 @@ module LoadedInGroupList class_methods do def with_counts(archived:) selects_including_counts = [ - 'namespaces.*', + "namespaces.*", "(#{project_count_sql(archived).to_sql}) AS preloaded_project_count", "(#{member_count_sql.to_sql}) AS preloaded_member_count", - "(#{subgroup_count_sql.to_sql}) AS preloaded_subgroup_count" + "(#{subgroup_count_sql.to_sql}) AS preloaded_subgroup_count", ] select(selects_including_counts) @@ -25,10 +25,10 @@ module LoadedInGroupList projects = Project.arel_table namespaces = Namespace.arel_table - base_count = projects.project(Arel.star.count.as('preloaded_project_count')) - .where(projects[:namespace_id].eq(namespaces[:id])) + base_count = projects.project(Arel.star.count.as("preloaded_project_count")) + .where(projects[:namespace_id].eq(namespaces[:id])) - if archived == 'only' + if archived == "only" base_count.where(projects[:archived].eq(true)) elsif Gitlab::Utils.to_boolean(archived) base_count @@ -39,9 +39,9 @@ module LoadedInGroupList def subgroup_count_sql namespaces = Namespace.arel_table - children = namespaces.alias('children') + children = namespaces.alias("children") - namespaces.project(Arel.star.count.as('preloaded_subgroup_count')) + namespaces.project(Arel.star.count.as("preloaded_subgroup_count")) .from(children) .where(children[:parent_id].eq(namespaces[:id])) end @@ -50,7 +50,7 @@ module LoadedInGroupList members = Member.arel_table namespaces = Namespace.arel_table - members.project(Arel.star.count.as('preloaded_member_count')) + members.project(Arel.star.count.as("preloaded_member_count")) .where(members[:source_type].eq(Namespace.name)) .where(members[:source_id].eq(namespaces[:id])) .where(members[:requested_at].eq(nil)) diff --git a/app/models/concerns/maskable.rb b/app/models/concerns/maskable.rb index 8793f0ec965..311847411a9 100644 --- a/app/models/concerns/maskable.rb +++ b/app/models/concerns/maskable.rb @@ -12,8 +12,8 @@ module Maskable REGEX = /\A\w{8,}\z/ included do - validates :masked, inclusion: { in: [true, false] } - validates :value, format: { with: REGEX }, if: :masked? + validates :masked, inclusion: {in: [true, false]} + validates :value, format: {with: REGEX}, if: :masked? end def to_runner_variable diff --git a/app/models/concerns/mentionable.rb b/app/models/concerns/mentionable.rb index 0d88b34fb48..cc6891d74d9 100644 --- a/app/models/concerns/mentionable.rb +++ b/app/models/concerns/mentionable.rb @@ -25,7 +25,7 @@ module Mentionable end if self < Participable - participant -> (user, ext) { all_references(user, extractor: ext) } + participant ->(user, ext) { all_references(user, extractor: ext) } end end @@ -82,7 +82,7 @@ module Mentionable end # Extract GFM references to other Mentionables from this Mentionable. Always excludes its #local_reference. - def referenced_mentionables(current_user = self.author) + def referenced_mentionables(current_user = author) return [] unless matches_cross_reference_regex? refs = all_references(current_user) @@ -97,10 +97,10 @@ module Mentionable # Allows heavy processing to be skipped def matches_cross_reference_regex? reference_pattern = if !project || project.default_issues_tracker? - ReferenceRegexes.default_pattern - else - ReferenceRegexes.external_pattern - end + ReferenceRegexes.default_pattern + else + ReferenceRegexes.external_pattern + end self.class.mentionable_attrs.any? do |attr, _| __send__(attr) =~ reference_pattern # rubocop:disable GitlabSecurity/PublicSend diff --git a/app/models/concerns/mentionable/reference_regexes.rb b/app/models/concerns/mentionable/reference_regexes.rb index b8fb3f71925..ffb4f8233c8 100644 --- a/app/models/concerns/mentionable/reference_regexes.rb +++ b/app/models/concerns/mentionable/reference_regexes.rb @@ -6,14 +6,14 @@ module Mentionable def self.reference_pattern(link_patterns, issue_pattern) Regexp.union(link_patterns, - issue_pattern, - *other_patterns) + issue_pattern, + *other_patterns) end def self.other_patterns [ Commit.reference_pattern, - MergeRequest.reference_pattern + MergeRequest.reference_pattern, ] end @@ -28,7 +28,7 @@ module Mentionable def self.external_pattern strong_memoize(:external_pattern) do issue_pattern = IssueTrackerService.reference_pattern - link_patterns = URI.regexp(%w(http https)) + link_patterns = URI.regexp(%w[http https]) reference_pattern(link_patterns, issue_pattern) end end diff --git a/app/models/concerns/milestoneish.rb b/app/models/concerns/milestoneish.rb index 055ffe04646..05aa8ba098e 100644 --- a/app/models/concerns/milestoneish.rb +++ b/app/models/concerns/milestoneish.rb @@ -3,7 +3,7 @@ module Milestoneish def closed_items_count(user) memoize_per_user(user, :closed_items_count) do - (count_issues_by_state(user)['closed'] || 0) + merge_requests.closed_and_merged.size + (count_issues_by_state(user)["closed"] || 0) + merge_requests.closed_and_merged.size end end @@ -47,15 +47,15 @@ module Milestoneish end def sorted_issues(user) - issues_visible_to_user(user).preload_associations.sort_by_attribute('label_priority') + issues_visible_to_user(user).preload_associations.sort_by_attribute("label_priority") end def sorted_merge_requests - merge_requests.sort_by_attribute('label_priority') + merge_requests.sort_by_attribute("label_priority") end def upcoming? - start_date && start_date.future? + start_date&.future? end def expires_at @@ -69,7 +69,7 @@ module Milestoneish end def expired? - due_date && due_date.past? + due_date&.past? end def group_milestone? diff --git a/app/models/concerns/mirror_authentication.rb b/app/models/concerns/mirror_authentication.rb index e3e1a0441f8..a2a7e1bf862 100644 --- a/app/models/concerns/mirror_authentication.rb +++ b/app/models/concerns/mirror_authentication.rb @@ -5,18 +5,18 @@ # serialized attribute. It also needs an `url` method to be defined module MirrorAuthentication SSH_PRIVATE_KEY_OPTS = { - type: 'RSA', - bits: 4096 + type: "RSA", + bits: 4096, }.freeze extend ActiveSupport::Concern included do - validates :auth_method, inclusion: { in: %w[password ssh_public_key] }, allow_blank: true + validates :auth_method, inclusion: {in: %w[password ssh_public_key]}, allow_blank: true # We should generate a key even if there's no SSH URL present before_validation :generate_ssh_private_key!, if: -> { - regenerate_ssh_private_key || ( auth_method == 'ssh_public_key' && ssh_private_key.blank? ) + regenerate_ssh_private_key || (auth_method == "ssh_public_key" && ssh_private_key.blank?) } credentials_field :auth_method, reader: false @@ -53,15 +53,15 @@ module MirrorAuthentication attr_accessor :regenerate_ssh_private_key def ssh_key_auth? - ssh_mirror_url? && auth_method == 'ssh_public_key' + ssh_mirror_url? && auth_method == "ssh_public_key" end def password_auth? - auth_method == 'password' + auth_method == "password" end def ssh_mirror_url? - url&.start_with?('ssh://') + url&.start_with?("ssh://") end def ssh_known_hosts_verified_by @@ -75,7 +75,7 @@ module MirrorAuthentication def auth_method auth_method = credentials.fetch(:auth_method, nil) if credentials.present? - auth_method.presence || 'password' + auth_method.presence || "password" end def ssh_public_key diff --git a/app/models/concerns/noteable.rb b/app/models/concerns/noteable.rb index 3c74034b527..0d8b6d15980 100644 --- a/app/models/concerns/noteable.rb +++ b/app/models/concerns/noteable.rb @@ -4,12 +4,12 @@ module Noteable extend ActiveSupport::Concern # `Noteable` class names that support resolvable notes. - RESOLVABLE_TYPES = %w(MergeRequest).freeze + RESOLVABLE_TYPES = %w[MergeRequest].freeze class_methods do # `Noteable` class names that support replying to individual notes. def replyable_types - %w(Issue MergeRequest) + %w[Issue MergeRequest] end end diff --git a/app/models/concerns/participable.rb b/app/models/concerns/participable.rb index 614c3242874..b78b3329673 100644 --- a/app/models/concerns/participable.rb +++ b/app/models/concerns/participable.rb @@ -64,9 +64,9 @@ module Participable private def all_participants - @all_participants ||= Hash.new do |hash, user| + @all_participants ||= Hash.new { |hash, user| hash[user] = raw_participants(user) - end + } end def raw_participants(current_user = nil) diff --git a/app/models/concerns/project_features_compatibility.rb b/app/models/concerns/project_features_compatibility.rb index f268a842db4..19c830fe569 100644 --- a/app/models/concerns/project_features_compatibility.rb +++ b/app/models/concerns/project_features_compatibility.rb @@ -4,7 +4,7 @@ # # After migrating issues_enabled merge_requests_enabled builds_enabled snippets_enabled and wiki_enabled # fields to a new table "project_features", support for the old fields is still needed in the API. -require 'gitlab/utils' +require "gitlab/utils" module ProjectFeaturesCompatibility extend ActiveSupport::Concern diff --git a/app/models/concerns/project_services_loggable.rb b/app/models/concerns/project_services_loggable.rb index fecd77cdc98..af1a2d4a99e 100644 --- a/app/models/concerns/project_services_loggable.rb +++ b/app/models/concerns/project_services_loggable.rb @@ -18,7 +18,7 @@ module ProjectServicesLoggable service_class: self.class.name, project_id: project.id, project_path: project.full_path, - message: message + message: message, }.merge(params) end diff --git a/app/models/concerns/prometheus_adapter.rb b/app/models/concerns/prometheus_adapter.rb index a29e80fe0c1..86bc522c418 100644 --- a/app/models/concerns/prometheus_adapter.rb +++ b/app/models/concerns/prometheus_adapter.rb @@ -40,10 +40,10 @@ module PrometheusAdapter { success: true, data: data, - last_update: Time.now.utc + last_update: Time.now.utc, } rescue Gitlab::PrometheusClient::Error => err - { success: false, result: err.message } + {success: false, result: err.message} end def query_klass_for(query_name) diff --git a/app/models/concerns/protected_ref.rb b/app/models/concerns/protected_ref.rb index af387c99f3d..26adb6cfc44 100644 --- a/app/models/concerns/protected_ref.rb +++ b/app/models/concerns/protected_ref.rb @@ -13,7 +13,7 @@ module ProtectedRef end def commit - project.commit(self.name) + project.commit(name) end class_methods do @@ -25,9 +25,9 @@ module ProtectedRef # If we don't `protected_branch` or `protected_tag` would be empty and # `project` cannot be delegated to it, which in turn would cause validations # to fail. - has_many :"#{type}_access_levels", inverse_of: self.model_name.singular + has_many :"#{type}_access_levels", inverse_of: model_name.singular - validates :"#{type}_access_levels", length: { is: 1, message: "are restricted to a single instance per #{self.model_name.human}." } + validates :"#{type}_access_levels", length: {is: 1, message: "are restricted to a single instance per #{model_name.human}."} accepts_nested_attributes_for :"#{type}_access_levels", allow_destroy: true end @@ -46,7 +46,7 @@ module ProtectedRef end def access_levels_for_ref(ref, action:, protected_refs: nil) - self.matching(ref, protected_refs: protected_refs) + matching(ref, protected_refs: protected_refs) .map(&:"#{action}_access_levels").flatten end @@ -57,13 +57,13 @@ module ProtectedRef # This method optionally takes in a list of `protected_refs` to search # through, to avoid calling out to the database. def matching(ref_name, protected_refs: nil) - (protected_refs || self.all).select { |protected_ref| protected_ref.matches?(ref_name) } + (protected_refs || all).select { |protected_ref| protected_ref.matches?(ref_name) } end end private def ref_matcher - @ref_matcher ||= RefMatcher.new(self.name) + @ref_matcher ||= RefMatcher.new(name) end end diff --git a/app/models/concerns/protected_ref_access.rb b/app/models/concerns/protected_ref_access.rb index 583751ea6ac..60e0ab45f11 100644 --- a/app/models/concerns/protected_ref_access.rb +++ b/app/models/concerns/protected_ref_access.rb @@ -4,9 +4,9 @@ module ProtectedRefAccess extend ActiveSupport::Concern HUMAN_ACCESS_LEVELS = { - Gitlab::Access::MAINTAINER => "Maintainers".freeze, - Gitlab::Access::DEVELOPER => "Developers + Maintainers".freeze, - Gitlab::Access::NO_ACCESS => "No one".freeze + Gitlab::Access::MAINTAINER => "Maintainers", + Gitlab::Access::DEVELOPER => "Developers + Maintainers", + Gitlab::Access::NO_ACCESS => "No one", }.freeze class_methods do @@ -14,7 +14,7 @@ module ProtectedRefAccess [ Gitlab::Access::MAINTAINER, Gitlab::Access::DEVELOPER, - Gitlab::Access::NO_ACCESS + Gitlab::Access::NO_ACCESS, ] end end @@ -23,19 +23,19 @@ module ProtectedRefAccess scope :master, -> { maintainer } # @deprecated scope :maintainer, -> { where(access_level: Gitlab::Access::MAINTAINER) } scope :developer, -> { where(access_level: Gitlab::Access::DEVELOPER) } - scope :by_user, -> (user) { where(user_id: user ) } - scope :by_group, -> (group) { where(group_id: group ) } + scope :by_user, ->(user) { where(user_id: user) } + scope :by_group, ->(group) { where(group_id: group) } scope :for_role, -> { where(user_id: nil, group_id: nil) } scope :for_user, -> { where.not(user_id: nil) } scope :for_group, -> { where.not(group_id: nil) } validates :access_level, presence: true, if: :role?, inclusion: { - in: self.allowed_access_levels + in: allowed_access_levels, } end def humanize - HUMAN_ACCESS_LEVELS[self.access_level] + HUMAN_ACCESS_LEVELS[access_level] end # CE access levels are always role-based, diff --git a/app/models/concerns/reactive_caching.rb b/app/models/concerns/reactive_caching.rb index de77ca3e963..bc686828aa2 100644 --- a/app/models/concerns/reactive_caching.rb +++ b/app/models/concerns/reactive_caching.rb @@ -118,11 +118,11 @@ module ReactiveCaching prefix = self.class.reactive_cache_key prefix = prefix.call(self) if prefix.respond_to?(:call) - ([prefix].flatten + qualifiers).join(':') + ([prefix].flatten + qualifiers).join(":") end def alive_reactive_cache_key(*qualifiers) - full_reactive_cache_key(*(qualifiers + ['alive'])) + full_reactive_cache_key(*(qualifiers + ["alive"])) end def locking_reactive_cache(*args) diff --git a/app/models/concerns/redactable.rb b/app/models/concerns/redactable.rb index 5ad96d6cc46..fbbb88f5935 100644 --- a/app/models/concerns/redactable.rb +++ b/app/models/concerns/redactable.rb @@ -26,7 +26,7 @@ module Redactable text = public_send(field) # rubocop:disable GitlabSecurity/PublicSend return unless text.present? - redacted = text.gsub(UNSUBSCRIBE_PATTERN, '/sent_notifications/REDACTED/unsubscribe') + redacted = text.gsub(UNSUBSCRIBE_PATTERN, "/sent_notifications/REDACTED/unsubscribe") public_send("#{field}=", redacted) # rubocop:disable GitlabSecurity/PublicSend end diff --git a/app/models/concerns/redis_cacheable.rb b/app/models/concerns/redis_cacheable.rb index 4bb4ffe2a8e..0e7d8a1af09 100644 --- a/app/models/concerns/redis_cacheable.rb +++ b/app/models/concerns/redis_cacheable.rb @@ -10,7 +10,7 @@ module RedisCacheable def cached_attr_reader(*attributes) attributes.each do |attribute| define_method(attribute) do - unless self.has_attribute?(attribute) + unless has_attribute?(attribute) raise ArgumentError, "`cached_attr_reader` requires the #{self.class.name}\##{attribute} attribute to have a database column" end @@ -36,7 +36,7 @@ module RedisCacheable private def cache_attribute_key - "cache:#{self.class.name}:#{self.id}:attributes" + "cache:#{self.class.name}:#{id}:attributes" end def cached_attributes diff --git a/app/models/concerns/referable.rb b/app/models/concerns/referable.rb index 58143a32fdc..5d21719fdff 100644 --- a/app/models/concerns/referable.rb +++ b/app/models/concerns/referable.rb @@ -20,7 +20,7 @@ module Referable # # Returns a String def to_reference(_from = nil, full:) - '' + "" end def reference_link_text(from = nil) @@ -52,7 +52,7 @@ module Referable # # Returns a String def reference_prefix - '' + "" end # Regexp pattern used to match references to this object diff --git a/app/models/concerns/relative_positioning.rb b/app/models/concerns/relative_positioning.rb index 46d2c345758..3cd21888a92 100644 --- a/app/models/concerns/relative_positioning.rb +++ b/app/models/concerns/relative_positioning.rb @@ -20,7 +20,7 @@ module RelativePositioning max_relative_position = objects.first.max_relative_position - self.transaction do + transaction do objects.each do |object| relative_position = position_between(max_relative_position, MAX_POSITION) object.relative_position = relative_position @@ -58,20 +58,20 @@ module RelativePositioning end def min_relative_position(&block) - calculate_relative_position('MIN', &block) + calculate_relative_position("MIN", &block) end def max_relative_position(&block) - calculate_relative_position('MAX', &block) + calculate_relative_position("MAX", &block) end def prev_relative_position prev_pos = nil - if self.relative_position - prev_pos = max_relative_position do |relation| - relation.where('relative_position < ?', self.relative_position) - end + if relative_position + prev_pos = max_relative_position { |relation| + relation.where("relative_position < ?", relative_position) + } end prev_pos @@ -80,10 +80,10 @@ module RelativePositioning def next_relative_position next_pos = nil - if self.relative_position - next_pos = min_relative_position do |relation| - relation.where('relative_position > ?', self.relative_position) - end + if relative_position + next_pos = min_relative_position { |relation| + relation.where("relative_position > ?", relative_position) + } end next_pos @@ -171,16 +171,16 @@ module RelativePositioning # MAX(relative_position) without the GROUP BY, due to index usage: # https://gitlab.com/gitlab-org/gitlab-ce/issues/54276#note_119340977 relation = self.class - .in_parents(parent_ids) - .order(Gitlab::Database.nulls_last_order('position', 'DESC')) - .limit(1) - .group(self.class.parent_column) + .in_parents(parent_ids) + .order(Gitlab::Database.nulls_last_order("position", "DESC")) + .limit(1) + .group(self.class.parent_column) relation = yield relation if block_given? relation .pluck(self.class.parent_column, "#{calculation}(relative_position) AS position") - .first&. - last + .first + &.last end end diff --git a/app/models/concerns/resolvable_discussion.rb b/app/models/concerns/resolvable_discussion.rb index c0490af2453..f017ffa585c 100644 --- a/app/models/concerns/resolvable_discussion.rb +++ b/app/models/concerns/resolvable_discussion.rb @@ -25,12 +25,11 @@ module ResolvableDiscussion delegate :potentially_resolvable?, to: :first_note - delegate :resolved_at, - :resolved_by, - :resolved_by_push?, - - to: :last_resolved_note, - allow_nil: true + delegate :resolved_at, + :resolved_by, + :resolved_by_push?, + to: :last_resolved_note, + allow_nil: true end def resolvable? @@ -63,7 +62,7 @@ module ResolvableDiscussion return unless resolved? strong_memoize(:last_resolved_note) do - resolved_notes.sort_by(&:resolved_at).last + resolved_notes.max_by(&:resolved_at) end end @@ -79,8 +78,8 @@ module ResolvableDiscussion return false unless current_user return false unless resolvable? - current_user == self.noteable.author || - current_user.can?(:resolve_note, self.project) + current_user == noteable.author || + current_user.can?(:resolve_note, project) end def resolve!(current_user) diff --git a/app/models/concerns/resolvable_note.rb b/app/models/concerns/resolvable_note.rb index 16ea330701d..878f6cc18c4 100644 --- a/app/models/concerns/resolvable_note.rb +++ b/app/models/concerns/resolvable_note.rb @@ -4,7 +4,7 @@ module ResolvableNote extend ActiveSupport::Concern # Names of all subclasses of `Note` that can be resolvable. - RESOLVABLE_TYPES = %w(DiffNote DiscussionNote).freeze + RESOLVABLE_TYPES = %w[DiffNote DiscussionNote].freeze included do belongs_to :resolved_by, class_name: "User" @@ -45,7 +45,7 @@ module ResolvableNote def resolved? return false unless resolvable? - self.resolved_at.present? + resolved_at.present? end def to_be_resolved? diff --git a/app/models/concerns/routable.rb b/app/models/concerns/routable.rb index b9ffc64e4a9..cbe4b3e239b 100644 --- a/app/models/concerns/routable.rb +++ b/app/models/concerns/routable.rb @@ -45,7 +45,7 @@ module Routable # clients' DBs) that have the same path with different cases. # See https://gitlab.com/gitlab-org/gitlab-ce/issues/18603. Also note that # our unique index is case-sensitive in Postgres. - binary = Gitlab::Database.mysql? ? 'BINARY' : '' + binary = Gitlab::Database.mysql? ? "BINARY" : "" order_sql = "(CASE WHEN #{binary} routes.path = #{connection.quote(path)} THEN 0 ELSE 1 END)" found = where_full_path_in([path]).reorder(order_sql).take return found if found @@ -54,7 +54,7 @@ module Routable if Gitlab::Database.postgresql? joins(:redirect_routes).find_by("LOWER(redirect_routes.path) = LOWER(?)", path) else - joins(:redirect_routes).find_by(redirect_routes: { path: path }) + joins(:redirect_routes).find_by(redirect_routes: {path: path}) end end end @@ -86,7 +86,7 @@ module Routable if wheres.empty? none else - joins(:route).where(wheres.join(' OR ')) + joins(:route).where(wheres.join(" OR ")) end end end @@ -100,12 +100,12 @@ module Routable end def full_path_components - full_path.split('/') + full_path.split("/") end def build_full_path if parent && path - parent.full_path + '/' + path + parent.full_path + "/" + path else path end @@ -119,8 +119,8 @@ module Routable private def set_path_errors - route_path_errors = self.errors.delete(:"route.path") - self.errors[:path].concat(route_path_errors) if route_path_errors + route_path_errors = errors.delete(:"route.path") + errors[:path].concat(route_path_errors) if route_path_errors end def full_name_changed? @@ -133,7 +133,7 @@ module Routable def build_full_name if parent && name - parent.human_name + ' / ' + name + parent.human_name + " / " + name else name end diff --git a/app/models/concerns/sha_attribute.rb b/app/models/concerns/sha_attribute.rb index a479bef993c..7ec07d2fc4e 100644 --- a/app/models/concerns/sha_attribute.rb +++ b/app/models/concerns/sha_attribute.rb @@ -5,7 +5,7 @@ module ShaAttribute class_methods do def sha_attribute(name) - return if ENV['STATIC_VERIFICATION'] + return if ENV["STATIC_VERIFICATION"] validate_binary_column_exists!(name) unless Rails.env.production? diff --git a/app/models/concerns/sortable.rb b/app/models/concerns/sortable.rb index 29e48f0c5f7..c1c8210f759 100644 --- a/app/models/concerns/sortable.rb +++ b/app/models/concerns/sortable.rb @@ -22,15 +22,15 @@ module Sortable class_methods do def order_by(method) case method.to_s - when 'created_asc' then order_created_asc - when 'created_date' then order_created_desc - when 'created_desc' then order_created_desc - when 'id_asc' then order_id_asc - when 'id_desc' then order_id_desc - when 'name_asc' then order_name_asc - when 'name_desc' then order_name_desc - when 'updated_asc' then order_updated_asc - when 'updated_desc' then order_updated_desc + when "created_asc" then order_created_asc + when "created_date" then order_created_desc + when "created_desc" then order_created_desc + when "id_asc" then order_id_asc + when "id_desc" then order_id_desc + when "name_asc" then order_name_asc + when "name_desc" then order_name_desc + when "updated_asc" then order_updated_asc + when "updated_desc" then order_updated_desc else all end @@ -50,7 +50,7 @@ module Sortable if target_type_column query.where("label_links.target_type = #{target_type_column}") else - query.where(label_links: { target_type: target_type }) + query.where(label_links: {target_type: target_type}) end query = query.where.not(title: excluded_labels) if excluded_labels.present? diff --git a/app/models/concerns/spammable.rb b/app/models/concerns/spammable.rb index 3ff4b4046d3..079ab6d693d 100644 --- a/app/models/concerns/spammable.rb +++ b/app/models/concerns/spammable.rb @@ -26,7 +26,7 @@ module Spammable end def submittable_as_spam_by?(current_user) - current_user && current_user.admin? && submittable_as_spam? + current_user&.admin? && submittable_as_spam? end def submittable_as_spam? @@ -39,13 +39,13 @@ module Spammable def check_for_spam error_msg = if Gitlab::Recaptcha.enabled? - "Your #{spammable_entity_type} has been recognized as spam. "\ - "Please, change the content or solve the reCAPTCHA to proceed." - else - "Your #{spammable_entity_type} has been recognized as spam and has been discarded." - end + "Your #{spammable_entity_type} has been recognized as spam. "\ + "Please, change the content or solve the reCAPTCHA to proceed." + else + "Your #{spammable_entity_type} has been recognized as spam and has been discarded." + end - self.errors.add(:base, error_msg) if spam? + errors.add(:base, error_msg) if spam? end def spammable_entity_type @@ -53,25 +53,25 @@ module Spammable end def spam_title - attr = self.class.spammable_attrs.find do |_, options| + attr = self.class.spammable_attrs.find { |_, options| options.fetch(:spam_title, false) - end + } public_send(attr.first) if attr && respond_to?(attr.first.to_sym) # rubocop:disable GitlabSecurity/PublicSend end def spam_description - attr = self.class.spammable_attrs.find do |_, options| + attr = self.class.spammable_attrs.find { |_, options| options.fetch(:spam_description, false) - end + } public_send(attr.first) if attr && respond_to?(attr.first.to_sym) # rubocop:disable GitlabSecurity/PublicSend end def spammable_text - result = self.class.spammable_attrs.map do |attr| + result = self.class.spammable_attrs.map { |attr| public_send(attr.first) # rubocop:disable GitlabSecurity/PublicSend - end + } result.reject(&:blank?).join("\n") end diff --git a/app/models/concerns/storage/legacy_namespace.rb b/app/models/concerns/storage/legacy_namespace.rb index 498996f4f80..fefc3b4a1c6 100644 --- a/app/models/concerns/storage/legacy_namespace.rb +++ b/app/models/concerns/storage/legacy_namespace.rb @@ -14,8 +14,8 @@ module Storage end parent_was = if parent_changed? && parent_id_was.present? - Namespace.find(parent_id_was) # raise NotFound early if needed - end + Namespace.find(parent_id_was) # raise NotFound early if needed + end move_repositories @@ -38,7 +38,7 @@ module Storage write_projects_repository_config rescue => e # Raise if development/test environment, else just notify Sentry - Gitlab::Sentry.track_exception(e, extra: { full_path_was: full_path_was, full_path: full_path, action: 'move_dir' }) + Gitlab::Sentry.track_exception(e, extra: {full_path_was: full_path_was, full_path: full_path, action: "move_dir"}) end true # false would cancel later callbacks but not rollback @@ -68,7 +68,7 @@ module Storage # if we cannot move namespace directory we should rollback # db changes in order to prevent out of sync between db and fs - raise Gitlab::UpdatePathError.new('namespace directory cannot be moved') + raise Gitlab::UpdatePathError.new("namespace directory cannot be moved") end end end @@ -82,7 +82,7 @@ module Storage # pending delete. Unscoping also get rids of the default order, which causes # problems with SELECT DISTINCT. Project.unscoped do - all_projects.select('distinct(repository_storage)').to_a.map(&:repository_storage) + all_projects.select("distinct(repository_storage)").to_a.map(&:repository_storage) end end @@ -94,7 +94,7 @@ module Storage new_path = "#{full_path}+#{id}+deleted" if gitlab_shell.mv_namespace(repository_storage, full_path, new_path) - Gitlab::AppLogger.info %Q(Namespace directory "#{full_path}" moved to "#{new_path}") + Gitlab::AppLogger.info %(Namespace directory "#{full_path}" moved to "#{new_path}") # Remove namespace directory async with delay so # GitLab has time to remove all projects first diff --git a/app/models/concerns/storage/legacy_project_wiki.rb b/app/models/concerns/storage/legacy_project_wiki.rb index a377fa1e5de..7c308ac9efa 100644 --- a/app/models/concerns/storage/legacy_project_wiki.rb +++ b/app/models/concerns/storage/legacy_project_wiki.rb @@ -5,7 +5,7 @@ module Storage extend ActiveSupport::Concern def disk_path - project.disk_path + '.wiki' + project.disk_path + ".wiki" end end end diff --git a/app/models/concerns/strip_attribute.rb b/app/models/concerns/strip_attribute.rb index c9f5ba7793d..af05b3c71d3 100644 --- a/app/models/concerns/strip_attribute.rb +++ b/app/models/concerns/strip_attribute.rb @@ -30,7 +30,7 @@ module StripAttribute def strip_attributes self.class.strip_attrs.each do |attr| - self[attr].strip! if self[attr] && self[attr].respond_to?(:strip!) + self[attr].strip! if self[attr]&.respond_to?(:strip!) end end end diff --git a/app/models/concerns/subscribable.rb b/app/models/concerns/subscribable.rb index 92a5c1112af..1f74f54e1db 100644 --- a/app/models/concerns/subscribable.rb +++ b/app/models/concerns/subscribable.rb @@ -32,8 +32,8 @@ module Subscribable def subscribers(project) relation = subscriptions_available(project) - .where(subscribed: true) - .select(:user_id) + .where(subscribed: true) + .select(:user_id) User.where(id: relation) end diff --git a/app/models/concerns/taskable.rb b/app/models/concerns/taskable.rb index f147ce8ad6b..c27792486dd 100644 --- a/app/models/concerns/taskable.rb +++ b/app/models/concerns/taskable.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'task_list' -require 'task_list/filter' +require "task_list" +require "task_list/filter" # Contains functionality for objects that can have task lists in their # descriptions. Task list items can be added with Markdown like "* [x] Fix @@ -9,8 +9,8 @@ require 'task_list/filter' # # Used by MergeRequest and Issue module Taskable - COMPLETED = 'completed'.freeze - INCOMPLETE = 'incomplete'.freeze + COMPLETED = "completed" + INCOMPLETE = "incomplete" COMPLETE_PATTERN = /(\[[xX]\])/.freeze INCOMPLETE_PATTERN = /(\[[\s]\])/.freeze ITEM_PATTERN = %r{ @@ -58,16 +58,16 @@ module Taskable # Return a string that describes the current state of this Taskable's task # list items, e.g. "12 of 20 tasks completed" def task_status(short: false) - return '' if description.blank? + return "" if description.blank? prep, completed = if short - ['/', ''] - else - [' of ', ' completed'] - end + ["/", ""] + else + [" of ", " completed"] + end sum = tasks.summary - "#{sum.complete_count}#{prep}#{sum.item_count} #{'task'.pluralize(sum.item_count)}#{completed}" + "#{sum.complete_count}#{prep}#{sum.item_count} #{"task".pluralize(sum.item_count)}#{completed}" end # Return a short string that describes the current state of this Taskable's diff --git a/app/models/concerns/time_trackable.rb b/app/models/concerns/time_trackable.rb index f61a0bbc65b..364bb6b7745 100644 --- a/app/models/concerns/time_trackable.rb +++ b/app/models/concerns/time_trackable.rb @@ -17,7 +17,7 @@ module TimeTrackable default_value_for :time_estimate, value: 0, allows_nil: false - validates :time_estimate, numericality: { message: 'has an invalid format' }, allow_nil: false + validates :time_estimate, numericality: {message: "has an invalid format"}, allow_nil: false validate :check_negative_time_spent has_many :timelogs, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent @@ -38,7 +38,7 @@ module TimeTrackable add_or_subtract_spent_time end end - alias_method :spend_time=, :spend_time + alias spend_time= spend_time # rubocop:enable Gitlab/ModuleWithInstanceVariables def total_time_spent @@ -77,7 +77,7 @@ module TimeTrackable return if time_spent.nil? || time_spent == :reset if time_spent < 0 && (time_spent.abs > original_total_time_spent) - errors.add(:time_spent, 'Time to subtract exceeds the total time spent') + errors.add(:time_spent, "Time to subtract exceeds the total time spent") end end diff --git a/app/models/concerns/token_authenticatable_strategies/base.rb b/app/models/concerns/token_authenticatable_strategies/base.rb index 01fb194281a..690bb5975a7 100644 --- a/app/models/concerns/token_authenticatable_strategies/base.rb +++ b/app/models/concerns/token_authenticatable_strategies/base.rb @@ -41,7 +41,7 @@ module TokenAuthenticatableStrategies def fallback? unless options[:fallback].in?([true, false, nil]) - raise ArgumentError, 'fallback: needs to be a boolean value!' + raise ArgumentError, "fallback: needs to be a boolean value!" end options[:fallback] == true @@ -49,7 +49,7 @@ module TokenAuthenticatableStrategies def migrating? unless options[:migrating].in?([true, false, nil]) - raise ArgumentError, 'migrating: needs to be a boolean value!' + raise ArgumentError, "migrating: needs to be a boolean value!" end options[:migrating] == true @@ -57,7 +57,7 @@ module TokenAuthenticatableStrategies def self.fabricate(model, field, options) if options[:digest] && options[:encrypted] - raise ArgumentError, 'Incompatible options set!' + raise ArgumentError, "Incompatible options set!" end if options[:digest] diff --git a/app/models/concerns/token_authenticatable_strategies/encrypted.rb b/app/models/concerns/token_authenticatable_strategies/encrypted.rb index 152491aa6e9..92a7da92c39 100644 --- a/app/models/concerns/token_authenticatable_strategies/encrypted.rb +++ b/app/models/concerns/token_authenticatable_strategies/encrypted.rb @@ -6,7 +6,7 @@ module TokenAuthenticatableStrategies super if migrating? && fallback? - raise ArgumentError, '`fallback` and `migrating` options are not compatible!' + raise ArgumentError, "`fallback` and `migrating` options are not compatible!" end end @@ -23,7 +23,7 @@ module TokenAuthenticatableStrategies elsif migrating? find_by_plaintext_token(token, unscoped) else - raise ArgumentError, 'Unknown encryption phase!' + raise ArgumentError, "Unknown encryption phase!" end end @@ -42,7 +42,7 @@ module TokenAuthenticatableStrategies return super if instance.has_attribute?(encrypted_field) if fully_encrypted? - raise ArgumentError, 'Using encrypted strategy when encrypted field is missing!' + raise ArgumentError, "Using encrypted strategy when encrypted field is missing!" else insecure_strategy.ensure_token(instance) end diff --git a/app/models/concerns/triggerable_hooks.rb b/app/models/concerns/triggerable_hooks.rb index c52baa0524c..c1bd157b4db 100644 --- a/app/models/concerns/triggerable_hooks.rb +++ b/app/models/concerns/triggerable_hooks.rb @@ -2,17 +2,17 @@ module TriggerableHooks AVAILABLE_TRIGGERS = { - repository_update_hooks: :repository_update_events, - push_hooks: :push_events, - tag_push_hooks: :tag_push_events, - issue_hooks: :issues_events, - confidential_note_hooks: :confidential_note_events, + repository_update_hooks: :repository_update_events, + push_hooks: :push_events, + tag_push_hooks: :tag_push_events, + issue_hooks: :issues_events, + confidential_note_hooks: :confidential_note_events, confidential_issue_hooks: :confidential_issues_events, - note_hooks: :note_events, - merge_request_hooks: :merge_requests_events, - job_hooks: :job_events, - pipeline_hooks: :pipeline_events, - wiki_page_hooks: :wiki_page_events + note_hooks: :note_events, + merge_request_hooks: :merge_requests_events, + job_hooks: :job_events, + pipeline_hooks: :pipeline_events, + wiki_page_hooks: :wiki_page_events, }.freeze extend ActiveSupport::Concern diff --git a/app/models/concerns/valid_attribute.rb b/app/models/concerns/valid_attribute.rb index 251db9ce30b..07e9a284d8b 100644 --- a/app/models/concerns/valid_attribute.rb +++ b/app/models/concerns/valid_attribute.rb @@ -7,6 +7,6 @@ module ValidAttribute # # +attribute+ The symbolised name of the attribute i.e :name def valid_attribute?(attribute) - self.errors.empty? || self.errors.messages[attribute].nil? + errors.empty? || errors.messages[attribute].nil? end end diff --git a/app/models/concerns/with_uploads.rb b/app/models/concerns/with_uploads.rb index 6c6febd186c..87ab13b80bd 100644 --- a/app/models/concerns/with_uploads.rb +++ b/app/models/concerns/with_uploads.rb @@ -23,12 +23,12 @@ module WithUploads # Currently there is no simple way how to select only not-mounted # uploads, it should be all FileUploaders so we select them by # `uploader` class - FILE_UPLOADERS = %w(PersonalFileUploader NamespaceFileUploader FileUploader).freeze + FILE_UPLOADERS = %w[PersonalFileUploader NamespaceFileUploader FileUploader].freeze included do has_many :uploads, as: :model has_many :file_uploads, -> { where(uploader: FILE_UPLOADERS) }, - class_name: 'Upload', as: :model, + class_name: "Upload", as: :model, dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent use_fast_destroy :file_uploads |