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| translations.each do |key, value|
next unless I18n.exists?(key, :en) 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| fix_plural_keys(key, value, locale).each do |plural|
plural_key = plural[0] plural_key = plural[0]
plural_value = plural[1] plural_value = plural[1]

View File

@ -463,7 +463,7 @@ class ApplicationController < ActionController::Base
return unless guardian.can_enable_safe_mode? return unless guardian.can_enable_safe_mode?
safe_mode = params[SAFE_MODE] safe_mode = params[SAFE_MODE]
if safe_mode&.is_a?(String) if safe_mode.is_a?(String)
safe_mode = safe_mode.split(",") safe_mode = safe_mode.split(",")
request.env[NO_THEMES] = safe_mode.include?(NO_THEMES) || safe_mode.include?(LEGACY_NO_THEMES) request.env[NO_THEMES] = safe_mode.include?(NO_THEMES) || safe_mode.include?(LEGACY_NO_THEMES)
request.env[NO_PLUGINS] = safe_mode.include?(NO_PLUGINS) 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 # Note the first is the default and we don't add a title
if (filter.to_s != current_homepage) && use_crawler_layout? 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 if list_opts[:category] && @category
@title = @title =

View File

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

View File

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

View File

@ -192,10 +192,10 @@ class UsersEmailController < ApplicationController
if token if token
if type == :old if type == :old
@change_request = @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 elsif type == :new
@change_request = @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
end end

View File

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

View File

@ -37,7 +37,7 @@ module Jobs
end end
end end
Rails.logger.warn( 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
end end

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -54,17 +54,17 @@ class IncomingEmail < ActiveRecord::Base
end end
def to_addresses=(to) 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) super(to)
end end
def cc_addresses=(cc) 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) super(cc)
end end
def from_address=(from) def from_address=(from)
from = from.first if from&.is_a?(Array) from = from.first if from.is_a?(Array)
super(from) super(from)
end end
end end

View File

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

View File

@ -451,7 +451,7 @@ class ThemeField < ActiveRecord::Base
self.theme.with_scss_load_paths do |load_paths| self.theme.with_scss_load_paths do |load_paths|
Stylesheet::Compiler.compile( 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.targets[self.target_id]}.scss",
theme: self.theme, theme: self.theme,
load_paths: load_paths, load_paths: load_paths,

View File

@ -30,10 +30,6 @@ class TopicTimer < ActiveRecord::Base
before_save do before_save do
self.created_at ||= Time.zone.now if execute_at self.created_at ||= Time.zone.now if execute_at
self.public_type = self.public_type? 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 end
# These actions are in place to make sure the topic is in the correct # 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 :primary_email, presence: true, unless: :skip_email_validation
validates :validatable_user_fields_values, watched_words: true, unless: :custom_fields_clean? validates :validatable_user_fields_values, watched_words: true, unless: :custom_fields_clean?
validates_associated :primary_email, 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 after_initialize :add_trust_level
@ -1619,8 +1619,6 @@ class User < ActiveRecord::Base
secondary_match.mark_for_destruction secondary_match.mark_for_destruction
primary_email.skip_validate_unique_email = true primary_email.skip_validate_unique_email = true
end end
new_email
end end
def emails def emails

View File

@ -78,7 +78,7 @@ class UserAvatar < ActiveRecord::Base
end end
end end
rescue OpenURI::HTTPError => e 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 ensure
tempfile&.close! tempfile&.close!
end end

View File

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

View File

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

View File

@ -139,8 +139,10 @@ class NotificationEmailer
email_user = EmailUser.new(notification, no_delay: no_delay) email_user = EmailUser.new(notification, no_delay: no_delay)
email_method = Notification.types[notification.notification_type] email_method = Notification.types[notification.notification_type]
DiscoursePluginRegistry.email_notification_filters.each do |filter| if DiscoursePluginRegistry.email_notification_filters.any? { |filter|
return unless filter.call(notification) !filter.call(notification)
}
return
end end
email_user.public_send(email_method) if email_user.respond_to? email_method 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) def self.push_notification(user, payload)
return if user.do_not_disturb? return if user.do_not_disturb?
DiscoursePluginRegistry.push_notification_filters.each do |filter| if DiscoursePluginRegistry.push_notification_filters.any? { |filter|
return unless filter.call(user, payload) !filter.call(user, payload)
}
return
end end
if user.push_subscriptions.exists? if user.push_subscriptions.exists?
@ -600,7 +602,7 @@ class PostAlerter
display_username: opts[:display_username] || post.user.username, 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] if group = opts[:group]
notification_data[:group_id] = group.id notification_data[:group_id] = group.id

View File

@ -67,7 +67,7 @@ class SidebarSiteSettingsBackfiller
SELECT SELECT
sidebar_section_links.user_id sidebar_section_links.user_id
FROM sidebar_section_links 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(",")}) AND sidebar_section_links.linkable_id IN (#{@removed_ids.join(",")})
SQL SQL
@ -83,7 +83,7 @@ class SidebarSiteSettingsBackfiller
SELECT SELECT
DISTINCT(sidebar_section_links.user_id) DISTINCT(sidebar_section_links.user_id)
FROM sidebar_section_links 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 sidebar_section_links.linkable_id IN (#{@added_ids.join(",")})
) AND users.id > 0 AND NOT users.staged ) AND users.id > 0 AND NOT users.staged
SQL SQL

View File

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

View File

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

View File

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

View File

@ -57,7 +57,7 @@ class BookmarkQuery
# this is purely to make the query easy to read and debug, otherwise it's # this is purely to make the query easy to read and debug, otherwise it's
# all mashed up into a massive ball in MiniProfiler :) # 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 end
.compact .compact

View File

@ -169,7 +169,7 @@ class Demon::EmailSync < ::Demon::Base
begin begin
data[:syncer]&.disconnect! data[:syncer]&.disconnect!
rescue Net::IMAP::ResponseError => err 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 end
end end

View File

@ -74,10 +74,12 @@ module DiscourseDev
def self.random(model, use_existing_records: true) def self.random(model, use_existing_records: true)
if !use_existing_records && model.new.respond_to?(:custom_fields) 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 end
count = model.count 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) offset = Faker::Number.between(from: 0, to: count - 1)
model.offset(offset).first 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}" "#{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( i.replace(
Nokogiri::HTML5.fragment( 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 rescue URI::Error
@ -517,9 +517,11 @@ module Email
"style" "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;" ] = "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 end
# rubocop:disable Lint/NonLocalExitFromIterator
return return
end end
return return
# rubocop:enable Lint/NonLocalExitFromIterator
end end
end end

View File

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

View File

@ -245,10 +245,10 @@ class FinalDestination
lambda do |chunk, _remaining_bytes, _total_bytes| lambda do |chunk, _remaining_bytes, _total_bytes|
response_body << chunk response_body << chunk
if response_body.bytesize > MAX_REQUEST_SIZE_BYTES 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 end
if Time.now - request_start_time > MAX_REQUEST_TIME_SECONDS 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
end end
@ -427,7 +427,7 @@ class FinalDestination
return true if @uri.port == 80 return true if @uri.port == 80
allowed_internal_hosts = 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.empty? || SiteSetting.s3_endpoint.blank?
return false if allowed_internal_hosts.none? { |aih| hostname_matches_s3_endpoint?(aih) } return false if allowed_internal_hosts.none? { |aih| hostname_matches_s3_endpoint?(aih) }

View File

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

View File

@ -420,7 +420,7 @@ class Guardian
end end
if (category = object.category) && category.read_restricted 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
end end

View File

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

View File

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

View File

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

View File

@ -2,10 +2,6 @@
class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
class CustomBuilder < MiniSql::Builder class CustomBuilder < MiniSql::Builder
def initialize(connection, sql)
super
end
def secure_category(secure_category_ids, category_alias = "c") def secure_category(secure_category_ids, category_alias = "c")
if secure_category_ids.present? if secure_category_ids.present?
where( where(
@ -21,7 +17,7 @@ class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
class ParamEncoder class ParamEncoder
def encode(*sql_array) 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) ActiveRecord::Base.public_send(:sanitize_sql_array, sql_array)
end end
end end

View File

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

View File

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

View File

@ -82,7 +82,7 @@ module Onebox
private private
def has_cached_body 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.cache_response_body?(uri.to_s) &&
body_cacher.cached_response_body_exists?(uri.to_s) body_cacher.cached_response_body_exists?(uri.to_s)
end end

View File

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

View File

@ -145,7 +145,7 @@ class Plugin::Instance
begin begin
"#{serializer.to_s.classify}Serializer".constantize "#{serializer.to_s.classify}Serializer".constantize
rescue StandardError rescue StandardError
"#{serializer.to_s}Serializer".constantize "#{serializer}Serializer".constantize
end end
# we have to work through descendants cause serializers may already be baked and cached # 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") if a.classes.include?("lightbox")
img = a.css("img[src]").first img = a.css("img[src]").first
srcset = img&.attributes["srcset"]&.value srcset = img&.attributes&.[]("srcset")&.value
if srcset if srcset
# if available, use the first image from the srcset here # if available, use the first image from the srcset here
# so we get the optimized image instead of the possibly huge original # so we get the optimized image instead of the possibly huge original

View File

@ -11,7 +11,7 @@ module PrettyText
key = "js." + key key = "js." + key
return I18n.t(key) if opts.blank? return I18n.t(key) if opts.blank?
str = I18n.t(key, Hash[opts.entries].symbolize_keys).dup 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 str
end end

View File

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

View File

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

View File

@ -63,7 +63,7 @@ class SiteSettings::DefaultsProvider
end end
def has_setting?(name) 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 end
private private

View File

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

View File

@ -15,7 +15,7 @@ module Stylesheet
file += options[:theme_variables].to_s file += options[:theme_variables].to_s
file += importer.theme_import(asset) file += importer.theme_import(asset)
elsif plugin_assets = Importer.plugin_assets[asset.to_s] 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? options[:load_paths] = [] if options[:load_paths].nil?
plugin_assets.each do |src| plugin_assets.each do |src|
file += File.read src file += File.read src

View File

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

View File

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

View File

@ -27,7 +27,7 @@ module Stylesheet
else else
# if plugin doesnt seem to be in our app, consider it as outside of the app # if plugin doesnt seem to be in our app, consider it as outside of the app
# and ignore it # 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
end end
@default_paths @default_paths
@ -109,7 +109,7 @@ module Stylesheet
targets = [] targets = []
if target.present? if target.present?
if DiscoursePluginRegistry.stylesheets_exists?(plugin_name, target.to_sym) if DiscoursePluginRegistry.stylesheets_exists?(plugin_name, target.to_sym)
targets.push("#{plugin_name}_#{target.to_s}") targets.push("#{plugin_name}_#{target}")
end end
else else
targets.push(plugin_name) targets.push(plugin_name)

View File

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

View File

@ -180,8 +180,8 @@ def generate_admin_sidebar_nav_map
end end
end end
# rubocop:disable Lint/Void
# Copy this JS to your browser to get the Ember routes. # Copy this JS to your browser to get the Ember routes.
#
<<~JS <<~JS
let routeMap = {} let routeMap = {}
for (const [key, value] of Object.entries( for (const [key, value] of Object.entries(
@ -208,6 +208,7 @@ def generate_admin_sidebar_nav_map
} }
console.log(JSON.stringify(routeMap)); console.log(JSON.stringify(routeMap));
JS JS
# rubocop:enable Lint/Void
# Paste the output below between ROUTE_MAP. # 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] base = args[:base]
raise "Unknown base: #{base.inspect}" unless %w[stable main].include?(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? raise "No branches specified in SECURITY_FIX_REFS env" if fix_refs.nil? || fix_refs.empty?
fix_refs.each do |ref| 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) 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.path.gsub!(%r{/info/refs\z}, "")
redirected_uri.query = nil redirected_uri.query = nil
redirected_uri 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 <" "Invalid version specifier operator for '#{req_operator} #{req_version}'. Operator must be one of <= or <"
end 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) resolved_requirement.satisfied_by?(parsed_target_version)
end end

View File

@ -111,7 +111,7 @@ module Chat
def should_create_revision(new_message, prev_message, guardian) def should_create_revision(new_message, prev_message, guardian)
max_seconds = SiteSetting.chat_editing_grace_period 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 return true if seconds_since_created > max_seconds
max_edited_chars = max_edited_chars =

View File

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

View File

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

View File

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

View File

@ -30,7 +30,7 @@ describe Chat::DirectMessage do
user3 = Fabricate.build(:user, username: "chatdmregent") user3 = Fabricate.build(:user, username: "chatdmregent")
users = [user1, user2, user3].concat( 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) direct_message = Fabricate(:direct_message, users: users)

View File

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

View File

@ -28,12 +28,12 @@ RSpec.describe "Channel message selection", type: :system do
chat.visit_channel(channel_1) chat.visit_channel(channel_1)
find(".chat-message-collapser-button").click 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 find(".chat-message-collapser-button").click
expect(page).to have_no_css(".chat-message-collapser-body.hidden") expect(page).to have_no_css(".chat-message-collapser-body.hidden")
find(".chat-img-upload").click find(".chat-img-upload").click
# visible false is because the upload doesnt exist but it's enough to know lightbox is working # 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
end end

View File

@ -181,10 +181,6 @@ module DiscourseNarrativeBot
archetype: Archetype.private_message, 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] if @data[:topic_id]
opts = opts.merge(topic_id: @data[:topic_id]).except(:title, :target_usernames, :archetype) opts = opts.merge(topic_id: @data[:topic_id]).except(:title, :target_usernames, :archetype)
end end

View File

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

View File

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

View File

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

View File

@ -2,7 +2,6 @@
require_relative "base" require_relative "base"
require "cgi" require "cgi"
require "set"
require "mysql2" require "mysql2"
require "htmlentities" require "htmlentities"
require "ruby-bbcode-to-md" 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' # 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" require "json"
if ARGV.length != 2 if ARGV.length != 2

View File

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

View File

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

View File

@ -620,7 +620,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Base
if DEBUG if DEBUG
raw = "Gallery ID: #{last_id}\n" + clean_up(gallery["raw"]) raw = "Gallery ID: #{last_id}\n" + clean_up(gallery["raw"])
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 end
raw += "#{clean_up(images.first["description"])}\n" raw += "#{clean_up(images.first["description"])}\n"
raw += "### #{gallery["caption"]}\n" raw += "### #{gallery["caption"]}\n"
@ -628,7 +628,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Base
raw += "#{UPLOADS}/#{gallery["orig"]}\n" raw += "#{UPLOADS}/#{gallery["orig"]}\n"
gallery_count += 1 gallery_count += 1
unless QUIET 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 end
{ {
id: "gallery#" + last_gallery["tid"].to_s + last_gallery["image_id"].to_s, 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) UserAvatar.import_url_for_user(avatar, newuser)
else else
filename = File.join(UPLOADS_DIR, avatar) 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 end
end, end,

View File

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

View File

@ -6,7 +6,6 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")
require "htmlentities" require "htmlentities"
require "tsort" require "tsort"
require "set"
require "optparse" require "optparse"
require "etc" require "etc"
require "open3" require "open3"
@ -369,7 +368,7 @@ class ImportScripts::Smf2 < ImportScripts::Base
end end
body.gsub!(XListPattern) do |s| body.gsub!(XListPattern) do |s|
r = +"\n[ul]" 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" "#{r}[/ul]\n"
end end

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,7 +6,7 @@ describe "Facebook OAuth2" do
let(:app_secret) { "adddcccdddd99922" } let(:app_secret) { "adddcccdddd99922" }
let(:temp_code) { "facebook_temp_code_544254" } let(:temp_code) { "facebook_temp_code_544254" }
let(:appsecret_proof) do 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 end
fab!(:user1) { Fabricate(:user) } fab!(:user1) { Fabricate(:user) }

View File

@ -27,7 +27,7 @@ RSpec.describe Jobs::BumpTopic do
expect do expect do
described_class.new.execute(topic_timer_id: topic.public_topic_timer.id) 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) expect(topic.reload.public_topic_timer).to eq(nil)
end end

View File

@ -7,9 +7,7 @@ RSpec.describe Jobs::InviteEmail do
end end
context "with an invite id" do context "with an invite id" do
let (:mailer) { let(:mailer) { Mail::Message.new(to: "eviltrout@test.domain") }
Mail::Message.new(to: "eviltrout@test.domain")
}
fab!(:invite) fab!(:invite)
it "delegates to the test mailer" do 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 it "handles errors from a troublesome check" do
AdminDashboardData.add_scheduled_problem_check(:test_identifier, TestCheck) do AdminDashboardData.add_scheduled_problem_check(:test_identifier, TestCheck) do
raise StandardError.new("something went wrong") raise StandardError.new("something went wrong")
AdminDashboardData::Problem.new("polling issue")
end end
described_class.new.execute(check_identifier: :test_identifier) described_class.new.execute(check_identifier: :test_identifier)

View File

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

View File

@ -205,7 +205,6 @@ RSpec.describe ContentSecurityPolicy do
end end
it "includes all EmbeddableHost" do it "includes all EmbeddableHost" do
EmbeddableHost
frame_ancestors = parse(policy)["frame-ancestors"] frame_ancestors = parse(policy)["frame-ancestors"]
expect(frame_ancestors).to include("https://a.org") expect(frame_ancestors).to include("https://a.org")
expect(frame_ancestors).to include("https://b.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 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").strip).to eq(Rails.root.to_s)
expect(Discourse::Utils.execute_command("pwd", chdir: "plugins").strip).to eq( expect(Discourse::Utils.execute_command("pwd", chdir: "plugins").strip).to eq(
"#{Rails.root.to_s}/plugins", "#{Rails.root}/plugins",
) )
end end
@ -477,12 +477,12 @@ RSpec.describe Discourse do
result = result =
Discourse::Utils.execute_command(chdir: "plugins") do |runner| 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") runner.exec("pwd")
end end
# Should return output of block # Should return output of block
expect(result.strip).to eq("#{Rails.root.to_s}/plugins") expect(result.strip).to eq("#{Rails.root}/plugins")
end end
it "does not leak chdir between threads" do it "does not leak chdir between threads" do

View File

@ -192,7 +192,7 @@ RSpec.describe DiscourseUpdates do
DiscourseUpdates.mark_new_features_as_seen(admin.id) DiscourseUpdates.mark_new_features_as_seen(admin.id)
expect(DiscourseUpdates.has_unseen_features?(admin.id)).to eq(false) expect(DiscourseUpdates.has_unseen_features?(admin.id)).to eq(false)
expect(DiscourseUpdates.new_features_last_seen(admin.id)).to be_within(1.second).of( expect(DiscourseUpdates.new_features_last_seen(admin.id)).to be_within(1.second).of(
last_item_date last_item_date,
) )
updated_features = [ updated_features = [

View File

@ -2298,8 +2298,7 @@ RSpec.describe Email::Receiver do
let(:user) { Fabricate(:user) } let(:user) { Fabricate(:user) }
let(:group) { Fabricate(:group, users: [user]) } let(:group) { Fabricate(:group, users: [user]) }
let (:email_1) { let(:email_1) { <<~EMAIL }
<<~EMAIL
MIME-Version: 1.0 MIME-Version: 1.0
Date: Wed, 01 Jan 2019 12:00:00 +0200 Date: Wed, 01 Jan 2019 12:00:00 +0200
Message-ID: <7aN1uwcokt2xkfG3iYrpKmiuVhy4w9b5@mail.gmail.com> Message-ID: <7aN1uwcokt2xkfG3iYrpKmiuVhy4w9b5@mail.gmail.com>
@ -2318,9 +2317,8 @@ RSpec.describe Email::Receiver do
libero quis, congue viverra sapien. Nulla sodales ac tellus a libero quis, congue viverra sapien. Nulla sodales ac tellus a
suscipit. suscipit.
EMAIL EMAIL
}
let (:post_2) { let(:post_2) do
incoming_email = incoming_email =
IncomingEmail.find_by(message_id: "7aN1uwcokt2xkfG3iYrpKmiuVhy4w9b5@mail.gmail.com") IncomingEmail.find_by(message_id: "7aN1uwcokt2xkfG3iYrpKmiuVhy4w9b5@mail.gmail.com")
@ -2330,10 +2328,9 @@ RSpec.describe Email::Receiver do
"Vestibulum rutrum tortor vitae arcu varius, non vestibulum ipsum tempor. Integer nibh libero, dignissim eu velit vel, interdum posuere mi. Aliquam erat volutpat. Pellentesque id nulla ultricies, eleifend ipsum non, fringilla purus. Aliquam pretium dolor lobortis urna volutpat, vel consectetur arcu porta. In non erat quis nibh gravida pharetra consequat vel risus. Aliquam rutrum consectetur est ac posuere. Praesent mattis nunc risus, a molestie lectus accumsan porta.", "Vestibulum rutrum tortor vitae arcu varius, non vestibulum ipsum tempor. Integer nibh libero, dignissim eu velit vel, interdum posuere mi. Aliquam erat volutpat. Pellentesque id nulla ultricies, eleifend ipsum non, fringilla purus. Aliquam pretium dolor lobortis urna volutpat, vel consectetur arcu porta. In non erat quis nibh gravida pharetra consequat vel risus. Aliquam rutrum consectetur est ac posuere. Praesent mattis nunc risus, a molestie lectus accumsan porta.",
topic_id: incoming_email.topic_id, topic_id: incoming_email.topic_id,
) )
} end
let (:email_3) { let(:email_3) { <<~EMAIL }
<<~EMAIL
MIME-Version: 1.0 MIME-Version: 1.0
Date: Wed, 01 Jan 2019 12:00:00 +0200 Date: Wed, 01 Jan 2019 12:00:00 +0200
References: <7aN1uwcokt2xkfG3iYrpKmiuVhy4w9b5@mail.gmail.com> <topic/#{post_2.topic_id}/#{post_2.id}@test.localhost> References: <7aN1uwcokt2xkfG3iYrpKmiuVhy4w9b5@mail.gmail.com> <topic/#{post_2.topic_id}/#{post_2.id}@test.localhost>
@ -2357,7 +2354,6 @@ RSpec.describe Email::Receiver do
iaculis mi, at hendrerit nisi turpis sit amet metus. Nulla egestas iaculis mi, at hendrerit nisi turpis sit amet metus. Nulla egestas
ante eget nisi luctus consectetur. ante eget nisi luctus consectetur.
EMAIL EMAIL
}
def receive(email_string) def receive(email_string)
Email::Receiver.new(email_string, destinations: [group]).process! Email::Receiver.new(email_string, destinations: [group]).process!

View File

@ -1389,9 +1389,7 @@ RSpec.describe Guardian do
end end
describe "a Post" do describe "a Post" do
let (:guardian) do let(:guardian) { Guardian.new(user) }
Guardian.new(user)
end
it "isn't allowed when not logged in" do it "isn't allowed when not logged in" do
expect(Guardian.new(nil).post_can_act?(post, :vote)).to be_falsey expect(Guardian.new(nil).post_can_act?(post, :vote)).to be_falsey
@ -2519,7 +2517,6 @@ RSpec.describe Guardian do
end end
let(:other_users_post_action) do let(:other_users_post_action) do
user.id = user.id
post.id = 1 post.id = 1
a = a =

View File

@ -78,7 +78,7 @@ RSpec.describe Onebox::Engine::GoogleMapsOnebox do
include_context "an engine", urltype: :short include_context "an engine", urltype: :short
URLS.each do |kind, t| URLS.each do |kind, t|
it "processes #{kind.to_s} url correctly", urltype: kind do it "processes #{kind} url correctly", urltype: kind do
expect(onebox.url).to eq t[:expect] expect(onebox.url).to eq t[:expect]
expect(onebox.streetview?).to t[:streetview] ? be_truthy : be_falsey expect(onebox.streetview?).to t[:streetview] ? be_truthy : be_falsey
expect(onebox.to_html).to include("<iframe") expect(onebox.to_html).to include("<iframe")

View File

@ -489,7 +489,7 @@ RSpec.describe Plugin::Instance do
).to eq(locale[:message_format]) ).to eq(locale[:message_format])
expect(JsLocaleHelper.find_moment_locale(["foo_BAR"])).to eq(locale[:moment_js]) expect(JsLocaleHelper.find_moment_locale(["foo_BAR"])).to eq(locale[:moment_js])
expect(JsLocaleHelper.find_moment_locale(["foo_BAR"], timezone_names: true)).to eq( expect(JsLocaleHelper.find_moment_locale(["foo_BAR"], timezone_names: true)).to eq(
locale[:moment_js_timezones] locale[:moment_js_timezones],
) )
end end

View File

@ -11,7 +11,7 @@ RSpec.describe ThemeSettingsParser do
class Loader class Loader
def initialize def initialize
@settings ||= [] @settings = []
load_settings load_settings
end end

View File

@ -2,7 +2,7 @@
RSpec.describe PasswordValidator do RSpec.describe PasswordValidator do
def password_error_message(key) def password_error_message(key)
I18n.t("activerecord.errors.models.user.attributes.password.#{key.to_s}") I18n.t("activerecord.errors.models.user.attributes.password.#{key}")
end end
subject(:validate) { validator.validate_each(record, :password, @password) } subject(:validate) { validator.validate_each(record, :password, @password) }

View File

@ -3,15 +3,13 @@
RSpec.describe RejectionMailer do RSpec.describe RejectionMailer do
describe "send_rejection" do describe "send_rejection" do
context "when sending rejection email" do context "when sending rejection email" do
fab! (:user) { fab!(:user) { Fabricate(:user) }
Fabricate(:user) let(:template_args) do
}
let (:template_args) {
{ former_title: "Mail Subject", destination: user.email, site_name: SiteSetting.title } { former_title: "Mail Subject", destination: user.email, site_name: SiteSetting.title }
} end
let (:reject_mail) { let(:reject_mail) do
RejectionMailer.send_rejection("email_reject_topic_not_found", user.email, template_args) RejectionMailer.send_rejection("email_reject_topic_not_found", user.email, template_args)
} end
it "renders the senders email" do it "renders the senders email" do
expect(reject_mail.to).to eql([user.email]) expect(reject_mail.to).to eql([user.email])

View File

@ -61,9 +61,7 @@ RSpec.describe Report do
] ]
# 60 complete days: # 60 complete days:
30 30.times.each do |i|
.times
.each_with_object(application_requests) do |i|
application_requests.concat( application_requests.concat(
[ [
{ {
@ -74,9 +72,7 @@ RSpec.describe Report do
], ],
) )
end end
30 30.times.each do |i|
.times
.each_with_object(application_requests) do |i|
application_requests.concat( application_requests.concat(
[ [
{ {
@ -1333,7 +1329,6 @@ RSpec.describe Report do
expect(page_view_anon_report[:color]).to eql("#9BC53D") expect(page_view_anon_report[:color]).to eql("#9BC53D")
expect(page_view_anon_report[:data][0][:y]).to eql(1) expect(page_view_anon_report[:data][0][:y]).to eql(1)
ensure
end end
end end
end end
@ -1378,7 +1373,6 @@ RSpec.describe Report do
expect(user_api_report[:color]).to eql("#9BC53D") expect(user_api_report[:color]).to eql("#9BC53D")
expect(user_api_report[:data][0][:y]).to eql(1) expect(user_api_report[:data][0][:y]).to eql(1)
ensure
end end
end end
end end

View File

@ -49,7 +49,6 @@ class RspecErrorTracker
RspecErrorTracker.last_exception = e RspecErrorTracker.last_exception = e
raise e raise e
end end
ensure
end end
end end

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