DEV: Fix various rubocop lints (#24749)

These (21 + 3 from previous PRs) are soon to be enabled in rubocop-discourse:

Capybara/VisibilityMatcher
Lint/DeprecatedOpenSSLConstant
Lint/DisjunctiveAssignmentInConstructor
Lint/EmptyConditionalBody
Lint/EmptyEnsure
Lint/LiteralInInterpolation
Lint/NonLocalExitFromIterator
Lint/ParenthesesAsGroupedExpression
Lint/RedundantCopDisableDirective
Lint/RedundantRequireStatement
Lint/RedundantSafeNavigation
Lint/RedundantStringCoercion
Lint/RedundantWithIndex
Lint/RedundantWithObject
Lint/SafeNavigationChain
Lint/SafeNavigationConsistency
Lint/SelfAssignment
Lint/UnreachableCode
Lint/UselessMethodDefinition
Lint/Void

Previous PRs:
Lint/ShadowedArgument
Lint/DuplicateMethods
Lint/BooleanSymbol
RSpec/SpecFilePathSuffix
This commit is contained in:
Jarek Radosz 2023-12-06 23:25:00 +01:00 committed by GitHub
parent 47f298b2f4
commit 694b5f108b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
129 changed files with 196 additions and 274 deletions

View File

@ -234,7 +234,7 @@ class Admin::SiteTextsController < Admin::AdminController
translations.each do |key, value|
next unless I18n.exists?(key, :en)
if value&.is_a?(Hash)
if value.is_a?(Hash)
fix_plural_keys(key, value, locale).each do |plural|
plural_key = plural[0]
plural_value = plural[1]

View File

@ -463,7 +463,7 @@ class ApplicationController < ActionController::Base
return unless guardian.can_enable_safe_mode?
safe_mode = params[SAFE_MODE]
if safe_mode&.is_a?(String)
if safe_mode.is_a?(String)
safe_mode = safe_mode.split(",")
request.env[NO_THEMES] = safe_mode.include?(NO_THEMES) || safe_mode.include?(LEGACY_NO_THEMES)
request.env[NO_PLUGINS] = safe_mode.include?(NO_PLUGINS)

View File

@ -92,7 +92,7 @@ class ListController < ApplicationController
# Note the first is the default and we don't add a title
if (filter.to_s != current_homepage) && use_crawler_layout?
filter_title = I18n.t("js.filters.#{filter.to_s}.title", count: 0)
filter_title = I18n.t("js.filters.#{filter}.title", count: 0)
if list_opts[:category] && @category
@title =

View File

@ -121,7 +121,7 @@ class TopicsController < ApplicationController
deleted =
guardian.can_see_topic?(ex.obj, false) ||
(!guardian.can_see_topic?(ex.obj) && ex.obj&.access_topic_via_group && ex.obj.deleted_at)
(!guardian.can_see_topic?(ex.obj) && ex.obj&.access_topic_via_group && ex.obj&.deleted_at)
if SiteSetting.detailed_404
if deleted
@ -975,7 +975,7 @@ class TopicsController < ApplicationController
rescue Discourse::InvalidAccess => ex
deleted =
guardian.can_see_topic?(ex.obj, false) ||
(!guardian.can_see_topic?(ex.obj) && ex.obj&.access_topic_via_group && ex.obj.deleted_at)
(!guardian.can_see_topic?(ex.obj) && ex.obj&.access_topic_via_group && ex.obj&.deleted_at)
raise Discourse::NotFound.new(
nil,

View File

@ -225,7 +225,7 @@ class UsersController < ApplicationController
end
end
if params[:external_ids]&.is_a?(ActionController::Parameters) && current_user&.admin? && is_api?
if params[:external_ids].is_a?(ActionController::Parameters) && current_user&.admin? && is_api?
attributes[:user_associated_accounts] = []
params[:external_ids].each do |provider_name, provider_uid|
@ -716,7 +716,7 @@ class UsersController < ApplicationController
# Handle associated accounts
associations = []
if params[:external_ids]&.is_a?(ActionController::Parameters) && current_user&.admin? && is_api?
if params[:external_ids].is_a?(ActionController::Parameters) && current_user&.admin? && is_api?
params[:external_ids].each do |provider_name, provider_uid|
authenticator = Discourse.enabled_authenticators.find { |a| a.name == provider_name }
raise Discourse::InvalidParameters.new(:external_ids) if !authenticator&.is_managed?

View File

@ -192,10 +192,10 @@ class UsersEmailController < ApplicationController
if token
if type == :old
@change_request =
token.user&.email_change_requests.where(old_email_token_id: token.id).first
token.user&.email_change_requests&.where(old_email_token_id: token.id)&.first
elsif type == :new
@change_request =
token.user&.email_change_requests.where(new_email_token_id: token.id).first
token.user&.email_change_requests&.where(new_email_token_id: token.id)&.first
end
end

View File

@ -7,9 +7,5 @@ module Jobs
def quit_email_early?
false
end
def execute(args)
super(args)
end
end
end

View File

@ -37,7 +37,7 @@ module Jobs
end
end
Rails.logger.warn(
"Completed syncing ACL for upload ids in #{time.to_s}. IDs: #{args[:upload_ids].join(", ")}",
"Completed syncing ACL for upload ids in #{time}. IDs: #{args[:upload_ids].join(", ")}",
)
end
end

View File

@ -14,7 +14,7 @@ module Jobs
poll_pop3 if should_poll?
DiscoursePluginRegistry.mail_pollers.each do |poller|
return if !poller.enabled?
next if !poller.enabled?
poller.poll_mailbox(method(:process_popmail))
end

View File

@ -279,7 +279,7 @@ class ApiKeyScope < ActiveRecord::Base
engine_mount_path = nil if engine_mount_path == "/"
set.routes.each do |route|
defaults = route.defaults
action = "#{defaults[:controller].to_s}##{defaults[:action]}"
action = "#{defaults[:controller]}##{defaults[:action]}"
path = route.path.spec.to_s.gsub(/\(\.:format\)/, "")
api_supported_path =
(

View File

@ -296,7 +296,6 @@ class Badge < ActiveRecord::Base
def long_description=(val)
self[:long_description] = val if val != long_description
val
end
def description
@ -311,7 +310,6 @@ class Badge < ActiveRecord::Base
def description=(val)
self[:description] = val if val != description
val
end
def slug

View File

@ -1,8 +1,6 @@
# frozen_string_literal: true
class ColorScheme < ActiveRecord::Base
# rubocop:disable Layout/HashAlignment
CUSTOM_SCHEMES = {
Dark: {
"primary" => "dddddd",
@ -279,8 +277,6 @@ class ColorScheme < ActiveRecord::Base
},
}
# rubocop:enable Layout/HashAlignment
LIGHT_THEME_ID = "Light"
def self.base_color_scheme_colors

View File

@ -38,7 +38,7 @@ module SecondFactorManager
end
def authenticate_totp(token)
totps = self&.user_second_factors.totps
totps = self&.user_second_factors&.totps
authenticated = false
totps.each do |totp|
last_used = 0
@ -64,20 +64,20 @@ module SecondFactorManager
def totp_enabled?
!SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
self&.user_second_factors.totps.exists?
self&.user_second_factors&.totps&.exists?
end
def backup_codes_enabled?
!SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
self&.user_second_factors.backup_codes.exists?
self&.user_second_factors&.backup_codes&.exists?
end
def security_keys_enabled?
!SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
self
&.security_keys
.where(factor_type: UserSecurityKey.factor_types[:second_factor], enabled: true)
.exists?
&.where(factor_type: UserSecurityKey.factor_types[:second_factor], enabled: true)
&.exists?
end
def has_any_second_factor_methods_enabled?

View File

@ -54,17 +54,17 @@ class IncomingEmail < ActiveRecord::Base
end
def to_addresses=(to)
to = to.map(&:downcase).join(";") if to&.is_a?(Array)
to = to.map(&:downcase).join(";") if to.is_a?(Array)
super(to)
end
def cc_addresses=(cc)
cc = cc.map(&:downcase).join(";") if cc&.is_a?(Array)
cc = cc.map(&:downcase).join(";") if cc.is_a?(Array)
super(cc)
end
def from_address=(from)
from = from.first if from&.is_a?(Array)
from = from.first if from.is_a?(Array)
super(from)
end
end

View File

@ -44,7 +44,7 @@ class TagUser < ActiveRecord::Base
tag_ids =
if tags.empty?
[]
elsif tags.first&.is_a?(String)
elsif tags.first.is_a?(String)
Tag.where_name(tags).pluck(:id)
else
tags

View File

@ -451,7 +451,7 @@ class ThemeField < ActiveRecord::Base
self.theme.with_scss_load_paths do |load_paths|
Stylesheet::Compiler.compile(
"#{prepended_scss} #{self.theme.scss_variables.to_s} #{self.value}",
"#{prepended_scss} #{self.theme.scss_variables} #{self.value}",
"#{Theme.targets[self.target_id]}.scss",
theme: self.theme,
load_paths: load_paths,

View File

@ -30,10 +30,6 @@ class TopicTimer < ActiveRecord::Base
before_save do
self.created_at ||= Time.zone.now if execute_at
self.public_type = self.public_type?
if (will_save_change_to_execute_at? && !attribute_in_database(:execute_at).nil?) ||
will_save_change_to_user_id?
end
end
# These actions are in place to make sure the topic is in the correct

View File

@ -153,7 +153,7 @@ class User < ActiveRecord::Base
validates :primary_email, presence: true, unless: :skip_email_validation
validates :validatable_user_fields_values, watched_words: true, unless: :custom_fields_clean?
validates_associated :primary_email,
message: ->(_, user_email) { user_email[:value]&.errors[:email]&.first }
message: ->(_, user_email) { user_email[:value]&.errors&.[](:email)&.first }
after_initialize :add_trust_level
@ -1619,8 +1619,6 @@ class User < ActiveRecord::Base
secondary_match.mark_for_destruction
primary_email.skip_validate_unique_email = true
end
new_email
end
def emails

View File

@ -78,7 +78,7 @@ class UserAvatar < ActiveRecord::Base
end
end
rescue OpenURI::HTTPError => e
raise e if e.io&.status[0].to_i != 404
raise e if e.io&.status&.[](0).to_i != 404
ensure
tempfile&.close!
end

View File

@ -607,7 +607,7 @@ class PostSerializer < BasicPostSerializer
end
def reviewable_scores
reviewable&.reviewable_scores&.to_a || []
reviewable&.reviewable_scores.to_a
end
def user_custom_fields_object

View File

@ -210,7 +210,7 @@ class InlineUploads
node["src"] = upload&.short_url || PLACEHOLDER
spaces_before = match[1].present? ? match[1][/ +$/].size : 0
replacement = +"#{" " * spaces_before}#{node.to_s}"
replacement = +"#{" " * spaces_before}#{node}"
yield(match[2], src, replacement, $~.offset(0)[0]) if block_given?
end

View File

@ -139,8 +139,10 @@ class NotificationEmailer
email_user = EmailUser.new(notification, no_delay: no_delay)
email_method = Notification.types[notification.notification_type]
DiscoursePluginRegistry.email_notification_filters.each do |filter|
return unless filter.call(notification)
if DiscoursePluginRegistry.email_notification_filters.any? { |filter|
!filter.call(notification)
}
return
end
email_user.public_send(email_method) if email_user.respond_to? email_method

View File

@ -51,8 +51,10 @@ class PostAlerter
def self.push_notification(user, payload)
return if user.do_not_disturb?
DiscoursePluginRegistry.push_notification_filters.each do |filter|
return unless filter.call(user, payload)
if DiscoursePluginRegistry.push_notification_filters.any? { |filter|
!filter.call(user, payload)
}
return
end
if user.push_subscriptions.exists?
@ -600,7 +602,7 @@ class PostAlerter
display_username: opts[:display_username] || post.user.username,
}
opts[:custom_data].each { |k, v| notification_data[k] = v } if opts[:custom_data]&.is_a?(Hash)
opts[:custom_data].each { |k, v| notification_data[k] = v } if opts[:custom_data].is_a?(Hash)
if group = opts[:group]
notification_data[:group_id] = group.id

View File

@ -67,7 +67,7 @@ class SidebarSiteSettingsBackfiller
SELECT
sidebar_section_links.user_id
FROM sidebar_section_links
WHERE sidebar_section_links.linkable_type = '#{@linkable_klass.to_s}'
WHERE sidebar_section_links.linkable_type = '#{@linkable_klass}'
AND sidebar_section_links.linkable_id IN (#{@removed_ids.join(",")})
SQL
@ -83,7 +83,7 @@ class SidebarSiteSettingsBackfiller
SELECT
DISTINCT(sidebar_section_links.user_id)
FROM sidebar_section_links
WHERE sidebar_section_links.linkable_type = '#{@linkable_klass.to_s}'
WHERE sidebar_section_links.linkable_type = '#{@linkable_klass}'
AND sidebar_section_links.linkable_id IN (#{@added_ids.join(",")})
) AND users.id > 0 AND NOT users.staged
SQL

View File

@ -314,7 +314,7 @@ class StaffActionLogger
UserHistory.create!(
params(opts).merge(
action: UserHistory.actions[:change_theme_setting],
subject: "#{theme.name}: #{setting_name.to_s}",
subject: "#{theme.name}: #{setting_name}",
previous_value: previous_value,
new_value: new_value,
),

View File

@ -126,7 +126,7 @@ Discourse.plugins.each do |plugin|
next if !plugin.metadata.url
Logster.config.project_directories << {
path: "#{Rails.root.to_s}/plugins/#{plugin.directory_name}",
path: "#{Rails.root}/plugins/#{plugin.directory_name}",
url: plugin.metadata.url,
}
end

View File

@ -23,12 +23,12 @@ listen ENV["UNICORN_LISTENER"] || "#{(ENV["UNICORN_BIND_ALL"] ? "" : "127.0.0.1:
FileUtils.mkdir_p("#{discourse_path}/tmp/pids") if !File.exist?("#{discourse_path}/tmp/pids")
# feel free to point this anywhere accessible on the filesystem
pid (ENV["UNICORN_PID_PATH"] || "#{discourse_path}/tmp/pids/unicorn.pid")
pid(ENV["UNICORN_PID_PATH"] || "#{discourse_path}/tmp/pids/unicorn.pid")
if ENV["RAILS_ENV"] != "production"
logger Logger.new(STDOUT)
# we want a longer timeout in dev cause first request can be really slow
timeout (ENV["UNICORN_TIMEOUT"] && ENV["UNICORN_TIMEOUT"].to_i || 60)
timeout(ENV["UNICORN_TIMEOUT"] && ENV["UNICORN_TIMEOUT"].to_i || 60)
else
# By default, the Unicorn logger will write to stderr.
# Additionally, some applications/frameworks log to stderr or stdout,

View File

@ -1,7 +1,6 @@
# frozen_string_literal: true
require "listen"
require "thread"
require "fileutils"
require "autospec/reload_css"
require "autospec/base_runner"
@ -267,7 +266,9 @@ class Autospec::Manager
if k.match(file)
puts "@@@@@@@@@@@@ #{file} matched a reloader for #{runner}" if @debug
runner.reload
# rubocop:disable Lint/NonLocalExitFromIterator
return
# rubocop:enable Lint/NonLocalExitFromIterator
end
end
# watchers

View File

@ -57,7 +57,7 @@ class BookmarkQuery
# this is purely to make the query easy to read and debug, otherwise it's
# all mashed up into a massive ball in MiniProfiler :)
"---- #{bookmarkable.model.to_s} bookmarkable ---\n\n #{interim_results.to_sql}"
"---- #{bookmarkable.model} bookmarkable ---\n\n #{interim_results.to_sql}"
end
.compact

View File

@ -169,7 +169,7 @@ class Demon::EmailSync < ::Demon::Base
begin
data[:syncer]&.disconnect!
rescue Net::IMAP::ResponseError => err
puts "[EmailSync] Encountered a response error when disconnecting: #{err.to_s}"
puts "[EmailSync] Encountered a response error when disconnecting: #{err}"
end
end
end

View File

@ -74,10 +74,12 @@ module DiscourseDev
def self.random(model, use_existing_records: true)
if !use_existing_records && model.new.respond_to?(:custom_fields)
model.joins(:_custom_fields).where("#{:type}_custom_fields.name = '#{AUTO_POPULATED}'")
model.joins(:_custom_fields).where(
"#{model.to_s.underscore}_custom_fields.name = '#{AUTO_POPULATED}'",
)
end
count = model.count
raise "#{:type} records are not yet populated" if count == 0
raise "#{model} records are not yet populated" if count == 0
offset = Faker::Number.between(from: 0, to: count - 1)
model.offset(offset).first

View File

@ -202,7 +202,7 @@ module Email
"#{src_uri.scheme || "https"}://#{src_uri.host}#{src_uri.path}#{src_uri.query.nil? ? "" : "?" + src_uri.query}#{src_uri.fragment.nil? ? "" : "#" + src_uri.fragment}"
i.replace(
Nokogiri::HTML5.fragment(
"<p><a href='#{src_uri.to_s}'>#{CGI.escapeHTML(display_src)}</a><p>",
"<p><a href='#{src_uri}'>#{CGI.escapeHTML(display_src)}</a><p>",
),
)
rescue URI::Error
@ -517,9 +517,11 @@ module Email
"style"
] = "background-color: #{bg_color}; color: #{SiteSetting.email_accent_fg_color}; border-top: 4px solid #{bg_color}; border-right: 6px solid #{bg_color}; border-bottom: 4px solid #{bg_color}; border-left: 6px solid #{bg_color}; display: inline-block; font-weight: bold;"
end
# rubocop:disable Lint/NonLocalExitFromIterator
return
end
return
# rubocop:enable Lint/NonLocalExitFromIterator
end
end

View File

@ -163,7 +163,6 @@ module FileStore
else
return true
end
return false
end
return false if SiteSetting.Upload.s3_cdn_url.blank?

View File

@ -245,10 +245,10 @@ class FinalDestination
lambda do |chunk, _remaining_bytes, _total_bytes|
response_body << chunk
if response_body.bytesize > MAX_REQUEST_SIZE_BYTES
raise Excon::Errors::ExpectationFailed.new("response size too big: #{@uri.to_s}")
raise Excon::Errors::ExpectationFailed.new("response size too big: #{@uri}")
end
if Time.now - request_start_time > MAX_REQUEST_TIME_SECONDS
raise Excon::Errors::ExpectationFailed.new("connect timeout reached: #{@uri.to_s}")
raise Excon::Errors::ExpectationFailed.new("connect timeout reached: #{@uri}")
end
end
@ -427,7 +427,7 @@ class FinalDestination
return true if @uri.port == 80
allowed_internal_hosts =
SiteSetting.allowed_internal_hosts&.split(/[|\n]/).filter_map { |aih| aih.strip.presence }
SiteSetting.allowed_internal_hosts&.split(/[|\n]/)&.filter_map { |aih| aih.strip.presence }
return false if allowed_internal_hosts.empty? || SiteSetting.s3_endpoint.blank?
return false if allowed_internal_hosts.none? { |aih| hostname_matches_s3_endpoint?(aih) }

View File

@ -26,7 +26,7 @@ class IPAddr
if mask == 32
to_s
else
"#{to_s}/#{mask}"
"#{self}/#{mask}"
end
else
nil

View File

@ -420,7 +420,7 @@ class Guardian
end
if (category = object.category) && category.read_restricted
return category.groups&.where(automatic: false).any? { |g| can_edit_group?(g) }
return category.groups&.where(automatic: false)&.any? { |g| can_edit_group?(g) }
end
end

View File

@ -38,7 +38,7 @@ module I18n
def self.sort_locale_files(files)
files.sort.sort_by do |filename|
matches = /(?:client|server)-([1-9]|[1-9][0-9]|100)\..+\.yml/.match(filename)
matches&.[](1)&.to_i || 0
matches&.[](1).to_i
end
end

View File

@ -141,7 +141,6 @@ module Imap
# This is done so we can extract X-GM-LABELS, X-GM-MSGID, and
# X-GM-THRID, all Gmail extended attributes.
#
# rubocop:disable Style/RedundantReturn
def msg_att(n)
match(T_LPAR)
attr = {}
@ -186,7 +185,7 @@ module Imap
end
attr[name] = val
end
return attr
attr
end
def label_data
@ -214,9 +213,8 @@ module Imap
result.push(atom)
end
end
return name, result
[name, result]
end
# rubocop:enable Style/RedundantReturn
end
end
end

View File

@ -14,10 +14,6 @@ module Middleware
],
)
def initialize(path)
super
end
def call(env)
# this is so so gnarly
# sometimes we leak out exceptions prior to creating a controller instance

View File

@ -2,10 +2,6 @@
class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
class CustomBuilder < MiniSql::Builder
def initialize(connection, sql)
super
end
def secure_category(secure_category_ids, category_alias = "c")
if secure_category_ids.present?
where(
@ -21,7 +17,7 @@ class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
class ParamEncoder
def encode(*sql_array)
# use active record to avoid any discrepencies
# use active record to avoid any discrepancies
ActiveRecord::Base.public_send(:sanitize_sql_array, sql_array)
end
end

View File

@ -6,7 +6,7 @@ module Onebox
SiteSetting
.blocked_onebox_domains
&.split("|")
.any? { |blocked| hostname == blocked || hostname.end_with?(".#{blocked}") }
&.any? { |blocked| hostname == blocked || hostname.end_with?(".#{blocked}") }
end
end
end

View File

@ -34,7 +34,6 @@ module Onebox
return @options if opt.nil? # make sure options provided
opt = opt.to_h if opt.instance_of?(OpenStruct)
@options.merge!(opt)
@options
end
def initialize(url, timeout = nil)

View File

@ -82,7 +82,7 @@ module Onebox
private
def has_cached_body
body_cacher&.respond_to?("cache_response_body?") &&
body_cacher.respond_to?("cache_response_body?") &&
body_cacher.cache_response_body?(uri.to_s) &&
body_cacher.cached_response_body_exists?(uri.to_s)
end

View File

@ -69,7 +69,6 @@ module Onebox
status = "success"
elsif raw["conclusion"] == "failure"
status = "failure"
elsif raw["conclusion"] == "cancelled"
end
elsif raw["status"] == "in_progress"
status = "pending"

View File

@ -145,7 +145,7 @@ class Plugin::Instance
begin
"#{serializer.to_s.classify}Serializer".constantize
rescue StandardError
"#{serializer.to_s}Serializer".constantize
"#{serializer}Serializer".constantize
end
# we have to work through descendants cause serializers may already be baked and cached

View File

@ -548,7 +548,7 @@ module PrettyText
if a.classes.include?("lightbox")
img = a.css("img[src]").first
srcset = img&.attributes["srcset"]&.value
srcset = img&.attributes&.[]("srcset")&.value
if srcset
# if available, use the first image from the srcset here
# so we get the optimized image instead of the possibly huge original

View File

@ -11,7 +11,7 @@ module PrettyText
key = "js." + key
return I18n.t(key) if opts.blank?
str = I18n.t(key, Hash[opts.entries].symbolize_keys).dup
opts.each { |k, v| str.gsub!("{{#{k.to_s}}}", v.to_s) }
opts.each { |k, v| str.gsub!("{{#{k}}}", v.to_s) }
str
end

View File

@ -34,7 +34,6 @@ class SecureSession
else
Discourse.redis.setex(prefixed_key(key), SecureSession.expiry.to_i, val.to_s)
end
val
end
private

View File

@ -1,7 +1,5 @@
# frozen_string_literal: true
require "thread"
class SidekiqPauser
TTL = 60
PAUSED_KEY = "sidekiq_is_paused_v2"

View File

@ -63,7 +63,7 @@ class SiteSettings::DefaultsProvider
end
def has_setting?(name)
has_key?(name.to_sym) || has_key?("#{name.to_s}?".to_sym) || name.to_sym == :default_locale
has_key?(name.to_sym) || has_key?("#{name}?".to_sym) || name.to_sym == :default_locale
end
private

View File

@ -268,7 +268,7 @@ class SiteSettings::TypeSupervisor
if (v = @validators[name])
validator = v[:class].new(v[:opts])
unless validator.valid_value?(val)
raise Discourse::InvalidParameters, "#{name.to_s}: #{validator.error_message}"
raise Discourse::InvalidParameters, "#{name}: #{validator.error_message}"
end
end

View File

@ -15,7 +15,7 @@ module Stylesheet
file += options[:theme_variables].to_s
file += importer.theme_import(asset)
elsif plugin_assets = Importer.plugin_assets[asset.to_s]
filename = "#{asset.to_s}.scss"
filename = "#{asset}.scss"
options[:load_paths] = [] if options[:load_paths].nil?
plugin_assets.each do |src|
file += File.read src

View File

@ -293,7 +293,7 @@ class Stylesheet::Manager
data = {
target: target,
theme_id: theme_id,
theme_name: theme&.name.downcase,
theme_name: theme&.name&.downcase,
remote: theme.remote_theme_id?,
}
builder = Builder.new(target: target, theme: theme, manager: self)

View File

@ -122,7 +122,7 @@ class Stylesheet::Manager::Builder
if is_theme?
"#{@target}_#{theme&.id}"
elsif @color_scheme
"#{@target}_#{scheme_slug}_#{@color_scheme&.id.to_s}_#{@theme&.id}"
"#{@target}_#{scheme_slug}_#{@color_scheme&.id}_#{@theme&.id}"
else
scheme_string = theme&.color_scheme ? "_#{theme.color_scheme.id}" : ""
"#{@target}#{scheme_string}"

View File

@ -27,7 +27,7 @@ module Stylesheet
else
# if plugin doesnt seem to be in our app, consider it as outside of the app
# and ignore it
warn("[stylesheet watcher] Ignoring outside of rails root plugin: #{plugin.path.to_s}")
warn("[stylesheet watcher] Ignoring outside of rails root plugin: #{plugin.path}")
end
end
@default_paths
@ -109,7 +109,7 @@ module Stylesheet
targets = []
if target.present?
if DiscoursePluginRegistry.stylesheets_exists?(plugin_name, target.to_sym)
targets.push("#{plugin_name}_#{target.to_s}")
targets.push("#{plugin_name}_#{target}")
end
else
targets.push(plugin_name)

View File

@ -480,7 +480,7 @@ class TestEmojiUpdate < Minitest::Test
puts "Runnings tests..."
reporter = Minitest::SummaryReporter.new
TestEmojiUpdate.run(reporter)
puts reporter.to_s
puts reporter
end
def image_path(style, name)

View File

@ -180,8 +180,8 @@ def generate_admin_sidebar_nav_map
end
end
# rubocop:disable Lint/Void
# Copy this JS to your browser to get the Ember routes.
#
<<~JS
let routeMap = {}
for (const [key, value] of Object.entries(
@ -207,7 +207,8 @@ def generate_admin_sidebar_nav_map
routeMap[key] = route;
}
console.log(JSON.stringify(routeMap));
JS
JS
# rubocop:enable Lint/Void
# Paste the output below between ROUTE_MAP.
#

View File

@ -384,7 +384,7 @@ task "version_bump:stage_security_fixes", [:base] do |t, args|
base = args[:base]
raise "Unknown base: #{base.inspect}" unless %w[stable main].include?(base)
fix_refs = ENV["SECURITY_FIX_REFS"]&.split(",").map(&:strip)
fix_refs = ENV["SECURITY_FIX_REFS"]&.split(",")&.map(&:strip)
raise "No branches specified in SECURITY_FIX_REFS env" if fix_refs.nil? || fix_refs.empty?
fix_refs.each do |ref|

View File

@ -62,7 +62,7 @@ class ThemeStore::GitImporter < ThemeStore::BaseImporter
redirected_uri = FinalDestination.resolve(first_clone_uri.to_s, http_verb: :get)
if redirected_uri&.path.ends_with?("/info/refs")
if redirected_uri&.path&.ends_with?("/info/refs")
redirected_uri.path.gsub!(%r{/info/refs\z}, "")
redirected_uri.query = nil
redirected_uri

View File

@ -69,7 +69,7 @@ module Discourse
"Invalid version specifier operator for '#{req_operator} #{req_version}'. Operator must be one of <= or <"
end
resolved_requirement = Gem::Requirement.new("#{req_operator} #{req_version.to_s}")
resolved_requirement = Gem::Requirement.new("#{req_operator} #{req_version}")
resolved_requirement.satisfied_by?(parsed_target_version)
end

View File

@ -111,7 +111,7 @@ module Chat
def should_create_revision(new_message, prev_message, guardian)
max_seconds = SiteSetting.chat_editing_grace_period
seconds_since_created = Time.now.to_i - new_message&.created_at.iso8601.to_time.to_i
seconds_since_created = Time.now.to_i - new_message&.created_at&.iso8601&.to_time.to_i
return true if seconds_since_created > max_seconds
max_edited_chars =

View File

@ -38,7 +38,7 @@ module Service
# context.fail!("failure": "something went wrong")
# @return [Context]
def fail!(context = {})
fail(context)
self.fail(context)
raise Failure, self
end

View File

@ -250,7 +250,7 @@ module Chat
thread_id = message_group.first.thread_id
if thread_id.present?
thread = Chat::Thread.find(thread_id)
if thread&.replies_count > 0
if thread&.replies_count&.> 0
open_bbcode_tag.add_thread_markdown(
thread_id: thread_id,
markdown: rendered_thread_markdown.join("\n"),

View File

@ -16,7 +16,7 @@ Fabricator(:chat_channel, class_name: "Chat::Channel") do
end
chatable { Fabricate(:category) }
type do |attrs|
if attrs[:chatable_type] == "Category" || attrs[:chatable]&.is_a?(Category)
if attrs[:chatable_type] == "Category" || attrs[:chatable].is_a?(Category)
"CategoryChannel"
else
"DirectMessageChannel"

View File

@ -30,7 +30,7 @@ describe Chat::DirectMessage do
user3 = Fabricate.build(:user, username: "chatdmregent")
users = [user1, user2, user3].concat(
5.times.map.with_index { |i| Fabricate(:user, username: "chatdmuser#{i}") },
5.times.map { |i| Fabricate(:user, username: "chatdmuser#{i}") },
)
direct_message = Fabricate(:direct_message, users: users)

View File

@ -153,7 +153,7 @@ RSpec.describe Chat::Api::ChannelsArchivesController do
expect { post "/chat/api/channels/#{channel.id}/archives" }.to change(
Jobs::Chat::ChannelArchive.jobs,
:size,
).by (1)
).by(1)
expect(response.status).to eq(200)
end
end

View File

@ -354,14 +354,14 @@ RSpec.describe Chat::ChatController do
sign_in(user)
expect {
post "/chat/dismiss-retention-reminder.json", params: { chatable_type: "Category" }
}.to change { user.user_option.reload.dismissed_channel_retention_reminder }.to (true)
}.to change { user.user_option.reload.dismissed_channel_retention_reminder }.to(true)
end
it "sets `dismissed_dm_retention_reminder` to true" do
sign_in(user)
expect {
post "/chat/dismiss-retention-reminder.json", params: { chatable_type: "DirectMessage" }
}.to change { user.user_option.reload.dismissed_dm_retention_reminder }.to (true)
}.to change { user.user_option.reload.dismissed_dm_retention_reminder }.to(true)
end
it "doesn't error if the fields are already true" do

View File

@ -9,7 +9,7 @@ RSpec::Matchers.define :match_response_schema do |schema|
JSON::Validator.validate!(schema_path, object, strict: true)
rescue JSON::Schema::ValidationError => e
puts "-- Printing response body after validation error\n"
pp object # rubocop:disable Lint/Debugger
pp object
raise e
end
end

View File

@ -28,12 +28,12 @@ RSpec.describe "Channel message selection", type: :system do
chat.visit_channel(channel_1)
find(".chat-message-collapser-button").click
expect(page).to have_css(".chat-message-collapser-body.hidden", visible: false)
expect(page).to have_css(".chat-message-collapser-body.hidden", visible: :hidden)
find(".chat-message-collapser-button").click
expect(page).to have_no_css(".chat-message-collapser-body.hidden")
find(".chat-img-upload").click
# visible false is because the upload doesnt exist but it's enough to know lightbox is working
expect(page).to have_css(".mfp-image-holder img[src*='#{image.url}']", visible: false)
expect(page).to have_css(".mfp-image-holder img[src*='#{image.url}']", visible: :hidden)
end
end

View File

@ -181,10 +181,6 @@ module DiscourseNarrativeBot
archetype: Archetype.private_message,
}
if @post && @post.topic.private_message? &&
@post.topic.topic_allowed_users.pluck(:user_id).include?(@user.id)
end
if @data[:topic_id]
opts = opts.merge(topic_id: @data[:topic_id]).except(:title, :target_usernames, :archetype)
end

View File

@ -67,7 +67,9 @@ module DiscoursePoll
)
post.errors.add(:base, error)
# rubocop:disable Lint/NonLocalExitFromIterator
return
# rubocop:enable Lint/NonLocalExitFromIterator
end
end

View File

@ -14,7 +14,6 @@ if ARGV.include?("bbcode-to-md")
end
require "pg"
require "set"
require "redcarpet"
require "htmlentities"
@ -29,8 +28,6 @@ class BulkImport::Base
NOW ||= "now()"
PRIVATE_OFFSET ||= 2**30
# rubocop:disable Layout/HashAlignment
CHARSET_MAP = {
"armscii8" => nil,
"ascii" => Encoding::US_ASCII,
@ -70,8 +67,6 @@ class BulkImport::Base
"utf8" => Encoding::UTF_8,
}
# rubocop:enable Layout/HashAlignment
def initialize
charset = ENV["DB_CHARSET"] || "utf8"
db = ActiveRecord::Base.connection_db_config.configuration_hash

View File

@ -1,7 +1,6 @@
# frozen_string_literal: true
require_relative "base"
require "set"
require "mysql2"
require "htmlentities"
require "parallel"

View File

@ -2,7 +2,6 @@
require_relative "base"
require "cgi"
require "set"
require "mysql2"
require "htmlentities"
require "ruby-bbcode-to-md"

View File

@ -6,7 +6,6 @@
# rbtrace -p 15193 -e 'Thread.new{require "objspace"; ObjectSpace.trace_object_allocations_start; GC.start(full_mark: true); ObjectSpace.dump_all(output: File.open("heap.json","w"))}.join'
#
#
require "set"
require "json"
if ARGV.length != 2

View File

@ -139,7 +139,7 @@ class ImportScripts::Bbpress < ImportScripts::Base
# make sure every user name has a unique email address
anon_names.each do |k, name|
if not emails.include? name["email"]
emails.push (name["email"])
emails.push(name["email"])
else
name["email"] = "anonymous_#{SecureRandom.hex}@no-email.invalid"
end

View File

@ -23,7 +23,6 @@
# You should run `rake posts:reorder_posts` after the import.
require "csv"
require "set"
require File.expand_path(File.dirname(__FILE__) + "/base.rb")
require "reverse_markdown" # gem 'reverse_markdown'

View File

@ -12,7 +12,6 @@ end
require "fileutils"
require "optparse"
require "set"
require "yaml"
DEFAULT_OUTPUT_PATH = "/shared/import/data"

View File

@ -620,7 +620,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Base
if DEBUG
raw = "Gallery ID: #{last_id}\n" + clean_up(gallery["raw"])
raw +=
"Cat: #{last_gallery["category"].to_s} - #{category_id_from_imported_category_id(last_gallery["category"].to_s + "gal")}"
"Cat: #{last_gallery["category"]} - #{category_id_from_imported_category_id(last_gallery["category"].to_s + "gal")}"
end
raw += "#{clean_up(images.first["description"])}\n"
raw += "### #{gallery["caption"]}\n"
@ -628,7 +628,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Base
raw += "#{UPLOADS}/#{gallery["orig"]}\n"
gallery_count += 1
unless QUIET
puts "#{gallery_count}--Cat: #{last_gallery["category"].to_s} ==> #{category_id_from_imported_category_id(last_gallery["category"].to_s + "gal")}"
puts "#{gallery_count}--Cat: #{last_gallery["category"]} ==> #{category_id_from_imported_category_id(last_gallery["category"].to_s + "gal")}"
end
{
id: "gallery#" + last_gallery["tid"].to_s + last_gallery["image_id"].to_s,

View File

@ -93,7 +93,7 @@ class ImportScripts::MyBB < ImportScripts::Base
UserAvatar.import_url_for_user(avatar, newuser)
else
filename = File.join(UPLOADS_DIR, avatar)
@uploader.create_avatar(newuser, filename) if File.exists?(filename)
@uploader.create_avatar(newuser, filename) if File.exist?(filename)
end
end
end,
@ -300,7 +300,7 @@ class ImportScripts::MyBB < ImportScripts::Base
ccf = cat.custom_fields
count += 1
next unless id = ccf["import_id"]
puts ("forum-#{id}.html --> /c/#{cat.id}") unless QUIET
puts("forum-#{id}.html --> /c/#{cat.id}") unless QUIET
begin
Permalink.create(url: "#{BASE}/forum-#{id}.html", category_id: cat.id)
rescue StandardError
@ -340,7 +340,7 @@ class ImportScripts::MyBB < ImportScripts::Base
nil
end
unless QUIET
puts ("#{BASE}/thread-#{id}.html --> http://localhost:3000/t/#{topic[:topic_id]}")
puts("#{BASE}/thread-#{id}.html --> http://localhost:3000/t/#{topic[:topic_id]}")
end
print_status(count, total_posts, start_time)
end

View File

@ -158,7 +158,7 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Base
username.gsub!(/[._]+/, "_") # can't have 2 special in a row
username.gsub!(/_+/, "_") # could result in dupes, but wtf?
username.gsub!(/_$/, "") # could result in dupes, but wtf?
print_warning ("#{olduser} --> #{username}") if olduser != username
print_warning("#{olduser} --> #{username}") if olduser != username
username
end

View File

@ -11,10 +11,6 @@ class ImportScripts::Sfn < ImportScripts::Base
BATCH_SIZE = 100_000
MIN_CREATED_AT = "2003-11-01"
def initialize
super
end
def execute
load_external_users
import_users

View File

@ -6,7 +6,6 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")
require "htmlentities"
require "tsort"
require "set"
require "optparse"
require "etc"
require "open3"
@ -369,7 +368,7 @@ class ImportScripts::Smf2 < ImportScripts::Base
end
body.gsub!(XListPattern) do |s|
r = +"\n[ul]"
s.lines.each { |l| "#{r}[li]#{l.strip.sub(/^\[x\]\s*/, "")}[/li]" }
s.lines.each { |l| r += "[li]#{l.strip.sub(/^\[x\]\s*/, "")}[/li]" }
"#{r}[/ul]\n"
end

View File

@ -2,7 +2,6 @@
require_relative "./socialcast_message.rb"
require_relative "./socialcast_user.rb"
require "set"
require File.expand_path(File.dirname(__FILE__) + "/../base.rb")
class ImportScripts::Socialcast < ImportScripts::Base

View File

@ -2,7 +2,6 @@
require_relative "./socialcast_message.rb"
require_relative "./socialcast_user.rb"
require "set"
require File.expand_path(File.dirname(__FILE__) + "/../base.rb")
MESSAGES_DIR = "output/messages"

View File

@ -4,7 +4,6 @@
#
require "ox"
require "set"
class Saxy < Ox::Sax
def initialize

View File

@ -382,7 +382,6 @@ class ImportScripts::ZendeskApi < ImportScripts::Base
html
else
puts "Error creating image upload"
"![](#{$1})"
exit
end
end

View File

@ -5,7 +5,6 @@ require 'fileutils'
require 'pathname'
require 'tmpdir'
require 'json'
require 'set'
def usage
STDERR.puts "Usage: memory-analysis [PID|DUMPFILE]"

View File

@ -5,4 +5,4 @@ Fabricator(:user_profile) do
user
end
Fabricator(:user_profile_long, from: :user_profile) { bio_raw ("trout" * 1000) }
Fabricator(:user_profile_long, from: :user_profile) { bio_raw("trout" * 1000) }

View File

@ -6,7 +6,7 @@ describe "Facebook OAuth2" do
let(:app_secret) { "adddcccdddd99922" }
let(:temp_code) { "facebook_temp_code_544254" }
let(:appsecret_proof) do
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, app_secret, access_token)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("SHA256"), app_secret, access_token)
end
fab!(:user1) { Fabricate(:user) }

View File

@ -8,11 +8,11 @@ RSpec.describe Jobs::BumpTopic do
topic = Fabricate(:topic_timer, user: admin).topic
create_post(topic: topic)
freeze_time (2.hours.from_now)
freeze_time(2.hours.from_now)
expect do
described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)
end.to change { topic.posts.count }.by (1)
end.to change { topic.posts.count }.by(1)
expect(topic.reload.public_topic_timer).to eq(nil)
end
@ -23,11 +23,11 @@ RSpec.describe Jobs::BumpTopic do
topic.category = Fabricate(:private_category, group: Fabricate(:group))
topic.save!
freeze_time (2.hours.from_now)
freeze_time(2.hours.from_now)
expect do
described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)
end.to change { topic.posts.count }.by (0)
end.not_to change { topic.posts.count }
expect(topic.reload.public_topic_timer).to eq(nil)
end

View File

@ -20,7 +20,7 @@ RSpec.describe Jobs::DeleteReplies do
it "can delete replies of a topic" do
SiteSetting.skip_auto_delete_reply_likes = 0
freeze_time (2.days.from_now)
freeze_time(2.days.from_now)
expect { described_class.new.execute(topic_timer_id: topic_timer.id) }.to change {
topic.posts.count
@ -33,7 +33,7 @@ RSpec.describe Jobs::DeleteReplies do
it "does not delete posts with likes over the threshold" do
SiteSetting.skip_auto_delete_reply_likes = 3
freeze_time (2.days.from_now)
freeze_time(2.days.from_now)
topic.posts.last.update!(like_count: SiteSetting.skip_auto_delete_reply_likes + 1)

View File

@ -10,7 +10,7 @@ RSpec.describe Jobs::DeleteTopic do
it "can delete a topic" do
first_post
freeze_time (2.hours.from_now)
freeze_time(2.hours.from_now)
described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)
expect(topic.reload).to be_trashed

View File

@ -161,7 +161,7 @@ RSpec.describe Jobs::EnqueueDigestEmails do
expect { Jobs::EnqueueDigestEmails.new.execute(nil) }.to change(
Jobs::UserEmail.jobs,
:size,
).by (1)
).by(1)
end
# The job didn't actually run, so fake the user_stat update
@ -171,7 +171,7 @@ RSpec.describe Jobs::EnqueueDigestEmails do
expect { Jobs::EnqueueDigestEmails.new.execute(nil) }.to change(
Jobs::UserEmail.jobs,
:size,
).by (1)
).by(1)
end
user1.user_stat.update(digest_attempted_at: Time.zone.now)

View File

@ -7,9 +7,7 @@ RSpec.describe Jobs::InviteEmail do
end
context "with an invite id" do
let (:mailer) {
Mail::Message.new(to: "eviltrout@test.domain")
}
let(:mailer) { Mail::Message.new(to: "eviltrout@test.domain") }
fab!(:invite)
it "delegates to the test mailer" do

View File

@ -92,7 +92,6 @@ RSpec.describe Jobs::ProblemCheck do
it "handles errors from a troublesome check" do
AdminDashboardData.add_scheduled_problem_check(:test_identifier, TestCheck) do
raise StandardError.new("something went wrong")
AdminDashboardData::Problem.new("polling issue")
end
described_class.new.execute(check_identifier: :test_identifier)

View File

@ -10,7 +10,7 @@ RSpec.describe Jobs::ProcessShelvedNotifications do
future = Fabricate(:do_not_disturb_timing, ends_at: 1.day.from_now)
past = Fabricate(:do_not_disturb_timing, starts_at: 2.day.ago, ends_at: 1.minute.ago)
expect { job.execute({}) }.to change { DoNotDisturbTiming.count }.by (-1)
expect { job.execute({}) }.to change { DoNotDisturbTiming.count }.by(-1)
expect(DoNotDisturbTiming.find_by(id: future.id)).to eq(future)
expect(DoNotDisturbTiming.find_by(id: past.id)).to eq(nil)
end

View File

@ -8,9 +8,6 @@ RSpec.describe Auth::DefaultCurrentUserProvider do
class TestProvider < Auth::DefaultCurrentUserProvider
attr_reader :env
def initialize(env)
super(env)
end
def cookie_jar
@cookie_jar ||= ActionDispatch::Request.new(env).cookie_jar

View File

@ -205,7 +205,6 @@ RSpec.describe ContentSecurityPolicy do
end
it "includes all EmbeddableHost" do
EmbeddableHost
frame_ancestors = parse(policy)["frame-ancestors"]
expect(frame_ancestors).to include("https://a.org")
expect(frame_ancestors).to include("https://b.org")

View File

@ -451,7 +451,7 @@ RSpec.describe Discourse do
it "works for individual commands" do
expect(Discourse::Utils.execute_command("pwd").strip).to eq(Rails.root.to_s)
expect(Discourse::Utils.execute_command("pwd", chdir: "plugins").strip).to eq(
"#{Rails.root.to_s}/plugins",
"#{Rails.root}/plugins",
)
end
@ -477,12 +477,12 @@ RSpec.describe Discourse do
result =
Discourse::Utils.execute_command(chdir: "plugins") do |runner|
expect(runner.exec("pwd").strip).to eq("#{Rails.root.to_s}/plugins")
expect(runner.exec("pwd").strip).to eq("#{Rails.root}/plugins")
runner.exec("pwd")
end
# Should return output of block
expect(result.strip).to eq("#{Rails.root.to_s}/plugins")
expect(result.strip).to eq("#{Rails.root}/plugins")
end
it "does not leak chdir between threads" do

Some files were not shown because too many files have changed in this diff Show More