RuboCop: Performance/MapCompact

[skip-stages=Flakey]

auto-corrected

Change-Id: I9e768e051924cfe58bf282f85d3cf6ca48735e9d
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/278264
Tested-by: Service Cloud Jenkins <svc.cloudjenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
QA-Review: Cody Cutrer <cody@instructure.com>
Product-Review: Cody Cutrer <cody@instructure.com>
This commit is contained in:
Cody Cutrer 2021-11-15 08:09:24 -07:00
parent 294d98c6fd
commit 58eb4175fb
118 changed files with 220 additions and 218 deletions

View File

@ -73,6 +73,8 @@ Naming/FileName:
Exclude:
- "**/Gemfile.d/~after.rb"
Performance/MapCompact:
Severity: error
Performance/RegexpMatch:
Severity: error
Performance/StartWith:

View File

@ -556,14 +556,14 @@ class AppointmentGroupsController < ApplicationController
ag_scope = ag_scope.where(id: ids) if ids.any?
# FIXME this could be a lot faster if we didn't look at eligibility to sign up.
# since the UI only cares about the date to jump to, it might not make a difference in many cases
events = ag_scope.preload(:appointments => :child_events).to_a.map do |ag|
events = ag_scope.preload(:appointments => :child_events).to_a.filter_map do |ag|
ag.appointments.detect do |appointment|
appointment.start_at > Time.zone.now &&
appointment.child_events_for(@current_user).empty? &&
(appointment.participants_per_appointment.nil? ||
appointment.child_events.count < appointment.participants_per_appointment)
end
end.compact
end
render :json => events.sort_by(&:start_at)[0..0].map { |event|
calendar_event_json(event, @current_user, session)
}

View File

@ -856,7 +856,7 @@ class CalendarEventsApiController < ApplicationController
get_all_pertinent_contexts(include_groups: true, favorites_first: true)
selected_contexts = @current_user.get_preference(:selected_calendar_contexts) || []
contexts = @contexts.map do |context|
contexts = @contexts.filter_map do |context|
next if context.try(:concluded?)
context_data = {
@ -879,7 +879,7 @@ class CalendarEventsApiController < ApplicationController
end
context_data
end.compact # remove any skipped contexts
end # remove any skipped contexts
render json: { contexts: StringifyIds.recursively_stringify_ids(contexts) }
end

View File

@ -181,7 +181,7 @@ class ContextModulesApiController < ApplicationController
end
end
render :json => modules_and_progressions.map { |mod, prog| module_json(mod, @student || @current_user, session, prog, includes, opts) }.compact
render :json => modules_and_progressions.filter_map { |mod, prog| module_json(mod, @student || @current_user, session, prog, includes, opts) }
end
end

View File

@ -542,7 +542,7 @@ class ContextModulesController < ApplicationController
tags = @context.context_module_tags.not_deleted.where(id: order)
affected_module_ids = (tags.map(&:context_module_id) + [@module.id]).uniq.compact
affected_items = []
items = order.map { |id| tags.detect { |t| t.id == id.to_i } }.compact.uniq
items = order.filter_map { |id| tags.detect { |t| t.id == id.to_i } }.uniq
items.each_with_index do |item, idx|
item.position = idx + 1
item.context_module_id = @module.id
@ -733,7 +733,7 @@ class ContextModulesController < ApplicationController
ActiveRecord::Associations::Preloader.new.preload(content_with_assignments, :assignment) if content_with_assignments.any?
if user_is_admin && should_preload_override_data?
assignments = assignment_tags.map(&:assignment).compact
assignments = assignment_tags.filter_map(&:assignment)
plain_quizzes = assignment_tags.select { |ct| ct.content.is_a?(Quizzes::Quiz) && !ct.content.assignment }.map(&:content)
preload_has_too_many_overrides(assignments, :assignment_id)

View File

@ -70,10 +70,10 @@ class CourseNicknamesController < ApplicationController
@current_user.shard.activate do
courses = Course.where(:id => value_records.map(&:sub_key)).to_a.index_by(&:id)
nicknames_json =
value_records.map do |record|
value_records.filter_map do |record|
course = courses[record.sub_key]
course && record.value && course_nickname_json(@current_user, course, record.value)
end.compact
end
render(:json => nicknames_json)
end

View File

@ -3634,9 +3634,9 @@ class CoursesController < ApplicationController
if params[:state]
states = Array(params[:state])
states += %w(created claimed) if states.include?('unpublished')
conditions = states.map do |state|
conditions = states.filter_map do |state|
Enrollment::QueryBuilder.new(nil, course_workflow_state: state, enforce_course_workflow_state: true).conditions
end.compact.join(" OR ")
end.join(" OR ")
enrollments = user.enrollments.eager_load(:course).where(conditions).shard(user.in_region_associated_shards)
if params[:enrollment_role]

View File

@ -917,9 +917,9 @@ class EnrollmentsApiController < ApplicationController
is_approved_parent = user.grants_right?(@current_user, :read_as_parent)
# otherwise check for read_roster rights on all of the requested
# user's accounts
approved_accounts = user.associated_root_accounts.map do |ra|
approved_accounts = user.associated_root_accounts.filter_map do |ra|
ra.id if is_approved_parent || ra.grants_right?(@current_user, session, :read_roster)
end.compact
end
# if there aren't any ids in approved_accounts, then the user doesn't have
# permissions.
@ -971,7 +971,7 @@ class EnrollmentsApiController < ApplicationController
if state.present?
if use_course_state
conditions = state.map { |s| Enrollment::QueryBuilder.new(s.to_sym).conditions }.compact
conditions = state.filter_map { |s| Enrollment::QueryBuilder.new(s.to_sym).conditions }
clauses << "(#{conditions.join(' OR ')})"
else
clauses << 'enrollments.workflow_state IN (:workflow_state)'

View File

@ -254,6 +254,6 @@ class EportfoliosController < ApplicationController
def stale_zip_file?
@attachment.created_at < 1.hour.ago ||
@attachment.created_at < (@portfolio.eportfolio_entries.map(&:updated_at).compact.max || @attachment.created_at)
@attachment.created_at < (@portfolio.eportfolio_entries.filter_map(&:updated_at).max || @attachment.created_at)
end
end

View File

@ -1238,7 +1238,7 @@ class ExternalToolsController < ApplicationController
tool_ids << t[:args][1] if t[:args] && t[:args][1]
end
@tools = ContextExternalTool.where(:id => tool_ids)
@tools = tool_ids.map { |id| @tools.find { |t| t[:id] == id } }.compact
@tools = tool_ids.filter_map { |id| @tools.find { |t| t[:id] == id } }
results = external_tools_json(@tools, course, @current_user, session).map do |result|
# add some identifying information here to simplify grouping by context for the consumer
result['context_id'] = course.id

View File

@ -162,14 +162,14 @@ class FeatureFlagsController < ApplicationController
skip_cache = @context.grants_right?(@current_user, session, :manage_feature_flags)
@context.feature_flags.load if skip_cache
flags = features.map { |fd|
flags = features.filter_map { |fd|
@context.lookup_feature_flag(fd.feature,
override_hidden: Account.site_admin.grants_right?(@current_user, session, :read),
skip_cache: skip_cache,
# Hide flags that are forced ON at a higher level
# Undocumented flag for frontend use only
hide_inherited_enabled: params[:hide_inherited_enabled])
}.compact
}
render json: flags.map { |flag| feature_with_flag_json(flag, @context, @current_user, session) }
end
@ -190,7 +190,7 @@ class FeatureFlagsController < ApplicationController
# ["fancy_wickets", "automatic_essay_grading", "telepathic_navigation"]
def enabled_features
if authorized_action(@context, @current_user, :read)
features = Feature.applicable_features(@context).map { |fd| @context.lookup_feature_flag(fd.feature) }.compact
features = Feature.applicable_features(@context).filter_map { |fd| @context.lookup_feature_flag(fd.feature) }
.select(&:enabled?).map(&:feature)
render json: features
end

View File

@ -1346,7 +1346,7 @@ class FilesController < ApplicationController
return true if verifier_checker.valid_verifier_for_permission?(params[:verifier], :read, session)
end
submissions = attachment.attachment_associations.where(context_type: "Submission").preload(:context).map(&:context).compact
submissions = attachment.attachment_associations.where(context_type: "Submission").preload(:context).filter_map(&:context)
return true if submissions.any? { |submission| submission.grants_right?(user, session, :read) }
course = api_find(Assignment, params[:assignment_id]).course unless params[:assignment_id].nil?

View File

@ -383,7 +383,7 @@ class GradeChangeAuditApiController < AuditorApiController
end
def anonymous_and_muted(events)
assignment_ids = events.map { |event| event["attributes"].fetch("assignment_id") }.compact
assignment_ids = events.filter_map { |event| event["attributes"].fetch("assignment_id") }
assignments = api_find_all(Assignment, assignment_ids)
assignments_anonymous_and_muted = {}

View File

@ -306,7 +306,7 @@ class GradebookHistoryApiController < ApplicationController
path = api_v1_gradebook_history_feed_url(@context, params.permit(:course_id, :assignment_id, :user_id, :ascending, :format))
indexed_versions = Api.paginate(indexed_versions, self, path)
ActiveRecord::Associations::Preloader.new.preload(indexed_versions, :version)
versions = indexed_versions.map(&:version).compact
versions = indexed_versions.filter_map(&:version)
render :json => versions_json(@context, versions, api_context(nil), :assignment => assignment, :student => student)
end

View File

@ -126,7 +126,7 @@ module Lti::IMS::Providers
end
def lti_roles
@_lti_roles ||= enrollments.map { |e| Lti::SubstitutionsHelper::LIS_V2_LTI_ADVANTAGE_ROLE_MAP[e.class] }.compact.flatten.uniq
@_lti_roles ||= enrollments.filter_map { |e| Lti::SubstitutionsHelper::LIS_V2_LTI_ADVANTAGE_ROLE_MAP[e.class] }.flatten.uniq
end
end

View File

@ -261,7 +261,7 @@ module Lti
def prep_tool_settings(parameters, tool_proxy, resource_link_id)
params = %w(LtiLink.custom.url ToolProxyBinding.custom.url ToolProxy.custom.url)
if parameters && (parameters.map { |p| p['variable'] }.compact & params).any?
if parameters && (parameters.filter_map { |p| p['variable'] } & params).any?
link = ToolSetting.where(
tool_proxy_id: tool_proxy.id,
context_id: @context.id,

View File

@ -74,7 +74,7 @@ class NotificationPreferencesController < ApplicationController
# Fetch all notification preference categories for the given communication channel
def category_index
policies = NotificationPolicy.find_all_for(@cc)
render json: { categories: policies.map { |p| p.notification.try(:category_slug) }.compact.uniq }
render json: { categories: policies.filter_map { |p| p.notification.try(:category_slug) }.uniq }
end
# @API Get a preference

View File

@ -384,7 +384,7 @@ class OutcomeResultsController < ApplicationController
rollups = user_rollups
@users = Api.paginate(@users, self, api_v1_course_outcome_rollups_url(@context))
rollups = @users.map { |u| rollups.find { |r| r.context.id == u.id } }.compact if params[:sort_by] == 'student'
rollups = @users.filter_map { |u| rollups.find { |r| r.context.id == u.id } } if params[:sort_by] == 'student'
json = outcome_results_rollups_json(rollups)
json[:meta] = Api.jsonapi_meta(@users, self, api_v1_course_outcome_rollups_url(@context))
json

View File

@ -329,7 +329,7 @@ class OutcomesApiController < ApplicationController
.where("submissions.user_id = ?", student_id)
.where("submissions.workflow_state <> 'deleted'")
quiz_alignments = quizzes.map do |quiz|
bank_ids = quiz.quiz_questions.map { |qq| qq.assessment_question.try(:assessment_question_bank_id) }.compact.uniq
bank_ids = quiz.quiz_questions.filter_map { |qq| qq.assessment_question.try(:assessment_question_bank_id) }.uniq
outcome_ids = ContentTag.active.where(content_id: bank_ids, content_type: "AssessmentQuestionBank", tag: "explicit_mastery").pluck(:learning_outcome_id)
outcome_ids.map do |id|
{

View File

@ -30,7 +30,7 @@ class Mutations::DeleteConversations < Mutations::BaseMutation
errors = {}
context[:deleted_models] = { conversations: {} }
# rubocop:disable Style/BlockDelimiters
resolved_ids = input[:ids].map { |id|
resolved_ids = input[:ids].filter_map { |id|
conversation = Conversation.find_by(id: id)
if conversation.nil?
errors[id] = "Unable to find Conversation"
@ -46,7 +46,7 @@ class Mutations::DeleteConversations < Mutations::BaseMutation
participant_record.remove_messages(:all)
context[:deleted_models][:conversations][conversation.id] = conversation
conversation.id
}.compact
}
# rubocop:enable Style/BlockDelimiters
response = {}

View File

@ -58,7 +58,7 @@ module AssignmentsHelper
multiple_due_dates
else
assignment = assignment.overridden_for(user)
due_date = assignment.due_at || assignment.applied_overrides.map(&:due_at).compact.first
due_date = assignment.due_at || assignment.applied_overrides.filter_map(&:due_at).first
due_date ? datetime_string(due_date) : I18n.t('No Due Date')
end
end

View File

@ -1264,7 +1264,7 @@ class Account < ActiveRecord::Base
end
end
else
@account_chain_ids ||= self.account_chain(:include_site_admin => true).map { |a| a.active? ? a.id : nil }.compact
@account_chain_ids ||= self.account_chain(:include_site_admin => true).filter_map { |a| a.active? ? a.id : nil }
Shard.partition_by_shard(@account_chain_ids) do |account_chain_ids|
if account_chain_ids == [Account.site_admin.id]
Account.site_admin.account_users_for(user)
@ -2036,7 +2036,7 @@ class Account < ActiveRecord::Base
def trusted_referers=(value)
self.settings[:trusted_referers] = unless value.blank?
value.split(',').map { |referer_url| format_referer(referer_url) }.compact.join(',')
value.split(',').filter_map { |referer_url| format_referer(referer_url) }.join(',')
end
end

View File

@ -152,14 +152,14 @@ class AppointmentGroup < ActiveRecord::Base
.flatten.map(&:asset_string)
@new_sub_context_codes -= disallowed_sub_context_codes
new_sub_contexts = @new_sub_context_codes.map { |code|
new_sub_contexts = @new_sub_context_codes.filter_map { |code|
next unless code =~ /\Acourse_section_(.*)/
cs = CourseSection.where(id: $1).first
AppointmentGroupSubContext.new(:appointment_group => self,
:sub_context => cs,
:sub_context_code => code)
}.compact
}
end
end

View File

@ -2380,7 +2380,7 @@ class Assignment < ActiveRecord::Base
# cap the number we will do
def too_many_qs_versions?(student_submissions)
qs_threshold = Setting.get("too_many_quiz_submission_versions", "150").to_i
qs_ids = student_submissions.map(&:quiz_submission_id).compact
qs_ids = student_submissions.filter_map(&:quiz_submission_id)
return false if qs_ids.empty?
Version.shard(shard).from(Version
@ -2446,7 +2446,7 @@ class Assignment < ActiveRecord::Base
visible_student_ids = visible_students_for_speed_grader(user: user, includes: includes).map(&:id).to_set
reps_and_others = groups_and_ungrouped(user, includes: includes).map do |group_name, group_info|
reps_and_others = groups_and_ungrouped(user, includes: includes).filter_map do |group_name, group_info|
group_students = group_info[:users]
visible_group_students = group_students.select { |u| visible_student_ids.include?(u.id) }
@ -2466,7 +2466,7 @@ class Assignment < ActiveRecord::Base
representative.short_name = group_name
[representative, others]
end.compact
end
sorted_reps_with_others =
Canvas::ICU.collate_by(reps_and_others) { |rep, _| rep.sortable_name }
@ -2559,7 +2559,7 @@ class Assignment < ActiveRecord::Base
zip_extractor = ZipExtractor.new(file.path)
# Creates a list of hashes, each one with a :user, :filename, and :submission entry.
@ignored_files = []
file_map = zip_extractor.unzip_files.map { |f| infer_comment_context_from_filename(f) }.compact
file_map = zip_extractor.unzip_files.filter_map { |f| infer_comment_context_from_filename(f) }
files_for_user = file_map.group_by { |f| f[:user] }
comments = []
@ -2839,12 +2839,12 @@ class Assignment < ActiveRecord::Base
# assignments only ever belong to courses, so we can reduce this to just IDs to simplify the db query
scope :for_context_codes, ->(codes) do
ids = codes.map do |code|
ids = codes.filter_map do |code|
type, id = parse_asset_string(code)
next unless type == 'Course'
id
end.compact
end
next none if ids.empty?
for_course(ids)
@ -3024,7 +3024,7 @@ class Assignment < ActiveRecord::Base
def readable_submission_types
return nil unless expects_submission? || expects_external_submission?
res = (self.submission_types || "").split(",").map { |s| readable_submission_type(s) }.compact
res = (self.submission_types || "").split(",").filter_map { |s| readable_submission_type(s) }
res.to_sentence(:or)
end

View File

@ -290,9 +290,9 @@ class AuthenticationProvider < ActiveRecord::Base
role_names = value.is_a?(String) ? value.split(',').map(&:strip) : value
account = pseudonym.account
existing_account_users = account.account_users.merge(user.account_users).preload(:role).to_a
roles = role_names.map do |role_name|
roles = role_names.filter_map do |role_name|
account.get_account_role_by_name(role_name)
end.compact
end
roles_to_add = roles - existing_account_users.map(&:role)
account_users_to_delete = existing_account_users.select { |au| au.active? && !roles.include?(au.role) }
account_users_to_activate = existing_account_users.select { |au| au.deleted? && roles.include?(au.role) }

View File

@ -264,7 +264,7 @@ class AuthenticationProvider::SAML < AuthenticationProvider::Delegated
self.idp_entity_id = entity.entity_id
self.log_in_url = idp.single_sign_on_services.find { |ep| ep.binding == SAML2::Bindings::HTTPRedirect::URN }.try(:location)
self.log_out_url = idp.single_logout_services.find { |ep| ep.binding == SAML2::Bindings::HTTPRedirect::URN }.try(:location)
self.certificate_fingerprint = idp.signing_keys.map(&:fingerprint).compact.join(' ').presence || idp.keys.first&.fingerprint
self.certificate_fingerprint = idp.signing_keys.filter_map(&:fingerprint).join(' ').presence || idp.keys.first&.fingerprint
recognized_formats = (idp.name_id_formats & self.class.name_id_formats)
if recognized_formats.length == 1
@ -274,8 +274,8 @@ class AuthenticationProvider::SAML < AuthenticationProvider::Delegated
self.identifier_format = SAML2::NameID::Format::UNSPECIFIED
end
self.settings[:signing_certificates] = idp.signing_keys.map(&:x509).compact
self.settings[:signing_keys] = idp.signing_keys.map(&:key).compact.map(&:to_s)
self.settings[:signing_certificates] = idp.signing_keys.filter_map(&:x509)
self.settings[:signing_keys] = idp.signing_keys.filter_map(&:key).map(&:to_s)
case idp.want_authn_requests_signed?
when true
# use ||= to not overwrite a specific algorithm that has otherwise been
@ -464,12 +464,12 @@ class AuthenticationProvider::SAML < AuthenticationProvider::Delegated
def self.private_keys
return {} unless (encryption = config[:encryption])
([encryption[:private_key]] + Array(encryption[:additional_private_keys])).map do |key|
([encryption[:private_key]] + Array(encryption[:additional_private_keys])).filter_map do |key|
path = resolve_saml_key_path(key)
next unless path
[path, File.read(path)]
end.compact.to_h
end.to_h
end
::Canvas::Reloader.on_reload do

View File

@ -380,8 +380,8 @@ class CalendarEvent < ActiveRecord::Base
if events.present?
CalendarEvent.where(:id => self)
.update_all(:start_at => events.map(&:start_at).compact.min,
:end_at => events.map(&:end_at).compact.max)
.update_all(:start_at => events.filter_map(&:start_at).min,
:end_at => events.filter_map(&:end_at).max)
reload
end
end

View File

@ -27,7 +27,7 @@ module ConditionalRelease
def begin_export(course, opts)
assignment_ids = nil
if opts[:selective]
assignment_ids = opts[:exported_assets].map { |asset| (match = asset.match(/assignment_(\d+)/)) && match[1] }.compact
assignment_ids = opts[:exported_assets].filter_map { |asset| (match = asset.match(/assignment_(\d+)/)) && match[1] }
return unless assignment_ids.any?
end

View File

@ -440,7 +440,7 @@ class ContentTag < ActiveRecord::Base
tags = tags.select([:id, :tag_type, :content_type, :context_module_id]).to_a
return if tags.empty?
module_ids = tags.map(&:context_module_id).compact
module_ids = tags.filter_map(&:context_module_id)
# update title
tag_ids = tags.select(&:sync_title_to_asset_title?).map(&:id)

View File

@ -191,7 +191,7 @@ class ContextExternalTool < ActiveRecord::Base
# look at the list of tools that are configured for the account and see if any are asking for permissions checks
Rails.cache.fetch_with_batched_keys("external_tools/global_navigation/permissions_to_check", batch_object: root_account, batched_keys: :global_navigation) do
tools = all_global_navigation_tools(root_account)
tools.map { |tool| tool.extension_setting(:global_navigation, 'required_permissions')&.split(",")&.map(&:to_sym) }.compact.flatten.uniq
tools.filter_map { |tool| tool.extension_setting(:global_navigation, 'required_permissions')&.split(",")&.map(&:to_sym) }.flatten.uniq
end
end

View File

@ -513,7 +513,7 @@ class Conversation < ActiveRecord::Base
def subscribed_participants
ActiveRecord::Associations::Preloader.new.preload(conversation_participants, :user) unless ModelCache[:users]
conversation_participants.select(&:subscribed?).map(&:user).compact
conversation_participants.select(&:subscribed?).filter_map(&:user)
end
def reply_from(opts)

View File

@ -1832,7 +1832,7 @@ class Course < ActiveRecord::Base
end
def self.find_all_by_context_code(codes)
ids = codes.map { |c| c.match(/\Acourse_(\d+)\z/)[1] rescue nil }.compact
ids = codes.filter_map { |c| c.match(/\Acourse_(\d+)\z/)[1] rescue nil }
Course.where(:id => ids).preload(:current_enrollments).to_a
end
@ -1899,7 +1899,7 @@ class Course < ActiveRecord::Base
def account_users_for(user)
@associated_account_ids ||= (self.associated_accounts + root_account.account_chain(include_site_admin: true))
.uniq.map { |a| a.active? ? a.id : nil }.compact
.uniq.filter_map { |a| a.active? ? a.id : nil }
Shard.partition_by_shard(@associated_account_ids) do |account_chain_ids|
if account_chain_ids == [Account.site_admin.id]
Account.site_admin.account_users_for(user)
@ -2745,7 +2745,7 @@ class Course < ActiveRecord::Base
scope.where("enrollments.course_section_id IN (?) OR (enrollments.limit_privileges_to_course_section=? AND enrollments.type IN ('TeacherEnrollment', 'TaEnrollment', 'DesignerEnrollment'))",
visibilities.map { |s| s[:course_section_id] }, false)
when :restricted
user_ids = visibilities.map { |s| s[:associated_user_id] }.compact
user_ids = visibilities.filter_map { |s| s[:associated_user_id] }
scope.where(enrollments: { user_id: (user_ids + [user&.id]).compact })
else
scope.none
@ -2785,7 +2785,7 @@ class Course < ActiveRecord::Base
case visibility
when :full then scope
when :sections then scope.where(enrollments: { course_section_id: visibilities.map { |s| s[:course_section_id] } })
when :restricted then scope.where(enrollments: { user_id: (visibilities.map { |s| s[:associated_user_id] }.compact + [user]) })
when :restricted then scope.where(enrollments: { user_id: (visibilities.filter_map { |s| s[:associated_user_id] } + [user]) })
when :limited then scope.where(enrollments: { type: ['StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'StudentViewEnrollment'] })
when :sections_limited then scope.where(enrollments: { course_section_id: visibilities.map { |s| s[:course_section_id] } })
.where(enrollments: { type: ['StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'StudentViewEnrollment'] })

View File

@ -134,7 +134,7 @@ class CourseProgress
return unless module_progressions
if module_progressions.is_a? Array
module_progressions.map(&:completed_at).compact.max
module_progressions.filter_map(&:completed_at).max
else
module_progressions.maximum(:completed_at)
end

View File

@ -918,7 +918,7 @@ class DiscussionTopic < ActiveRecord::Base
def self.preload_can_unpublish(context, topics, assmnt_ids_with_subs = nil)
return unless topics.any?
assmnt_ids_with_subs ||= Assignment.assignment_ids_with_submissions(topics.map(&:assignment_id).compact)
assmnt_ids_with_subs ||= Assignment.assignment_ids_with_submissions(topics.filter_map(&:assignment_id))
student_ids = context.all_real_student_enrollments.select(:user_id)
topic_ids_with_entries = DiscussionEntry.active.where(discussion_topic_id: topics)
@ -1585,7 +1585,7 @@ class DiscussionTopic < ActiveRecord::Base
attachments.each do |attachment|
attachment.podcast_associated_asset = messages_hash[attachment.id.to_s]
end
media_object_ids -= attachments.map(&:media_entry_id).compact # don't include media objects if the file is already included
media_object_ids -= attachments.filter_map(&:media_entry_id) # don't include media objects if the file is already included
media_objects = media_object_ids.empty? ? [] : MediaObject.where(media_id: media_object_ids).to_a
media_objects = media_objects.uniq(&:media_id)
@ -1604,7 +1604,7 @@ class DiscussionTopic < ActiveRecord::Base
def self.to_podcast(elements)
require 'rss/2.0'
elements.map do |elem|
elements.filter_map do |elem|
asset = elem.podcast_associated_asset
next unless asset
@ -1641,7 +1641,7 @@ class DiscussionTopic < ActiveRecord::Base
item.enclosure = RSS::Rss::Channel::Item::Enclosure.new(url, size, content_type)
end
item
end.compact
end
end
def initial_post_required?(user, session = nil)

View File

@ -126,7 +126,7 @@ class DiscussionTopic::MaterializedView < ActiveRecord::Base
@for_mobile = true if opts[:include_mobile_overrides]
new_entries = all_entries.count != entry_ids.count ? all_entries.where.not(:id => entry_ids).to_a : []
participant_ids = (Set.new(participant_ids) + new_entries.map(&:user_id).compact + new_entries.map(&:editor_id).compact).to_a
participant_ids = (Set.new(participant_ids) + new_entries.filter_map(&:user_id) + new_entries.filter_map(&:editor_id)).to_a
entry_ids = (Set.new(entry_ids) + new_entries.map(&:id)).to_a
new_entries_json_structure = discussion_entry_api_json(new_entries, discussion_topic.context, nil, nil, [])
else

View File

@ -1411,7 +1411,7 @@ class Enrollment < ActiveRecord::Base
# overrides, etc. but if it doesn't find anything, start guessing by
# looking at the enrollment, section, course, then term. if we still didn't
# find it, fall back to the section or course creation date.
enrollment_dates.map(&:first).compact.min ||
enrollment_dates.filter_map(&:first).min ||
start_at ||
course_section&.start_at ||
course.start_at ||
@ -1424,7 +1424,7 @@ class Enrollment < ActiveRecord::Base
# try and use the enrollment dates logic first, since it knows about
# overrides, etc. but if it doesn't find anything, start guessing by
# looking at the enrollment, section, course, then term.
enrollment_dates.map(&:last).compact.max ||
enrollment_dates.filter_map(&:last).max ||
end_at ||
course_section&.end_at ||
course.conclude_at ||

View File

@ -158,14 +158,14 @@ class EnrollmentState < ActiveRecord::Base
self.state_started_at = start_at
self.state_valid_until = end_at # stores the next date trigger
else
global_start_at = ranges.map(&:compact).map(&:min).compact.min
global_start_at = ranges.map(&:compact).filter_map(&:min).min
if !global_start_at
# Not strictly within any range so no translation needed
self.state = wf_state
elsif global_start_at < now
# we've past the end date so no matter what the state was, we're "completed" now
self.state_started_at = ranges.map(&:last).compact.min
self.state_started_at = ranges.filter_map(&:last).min
self.state = 'completed'
elsif self.enrollment.fake_student? # rubocop:disable Lint/DuplicateBranch
# Allow student view students to use the course before the term starts

View File

@ -71,7 +71,7 @@ class ExternalFeed < ActiveRecord::Base
end
def add_rss_entries(rss)
items = rss.items.map { |item| add_entry(item, rss, :rss) }.compact
items = rss.items.filter_map { |item| add_entry(item, rss, :rss) }
self.context.add_aggregate_entries(items, self) if self.context.respond_to?(:add_aggregate_entries)
items
end

View File

@ -96,9 +96,9 @@ class GoogleDocsCollaboration < Collaboration
nil
end
user_ids = new_users.map do |user|
user_ids = new_users.filter_map do |user|
google_user_service(user, GOOGLE_DRIVE_SERVICE).service_user_id rescue nil
end.compact
end
google_adapter_for_user.acl_add(self.document_id, user_ids, domain)
end

View File

@ -266,7 +266,7 @@ class Group < ActiveRecord::Base
end
def self.find_all_by_context_code(codes)
ids = codes.map { |c| c.match(/\Agroup_(\d+)\z/)[1] rescue nil }.compact
ids = codes.filter_map { |c| c.match(/\Agroup_(\d+)\z/)[1] rescue nil }
Group.find(ids)
end
@ -445,7 +445,7 @@ class Group < ActiveRecord::Base
invitees << User.where(id: key.to_i).first if val != '0'
end
end
invitees.compact.map { |i| self.invite_user(i) }.compact
invitees.compact.filter_map { |i| self.invite_user(i) }
end
def peer_groups

View File

@ -66,7 +66,7 @@ module Importers
bank.mark_as_importing!(migration)
next if bank.edit_types_locked_for_overwrite_on_import.include?(:content)
aq_ids = questions.select { |aq| aq["question_bank_migration_id"] == mig_id }.map { |aq| aq["assessment_question_id"] }.compact
aq_ids = questions.select { |aq| aq["question_bank_migration_id"] == mig_id }.filter_map { |aq| aq["assessment_question_id"] }
bank.assessment_questions.active.where.not(:migration_id => aq_ids).update_all(:workflow_state => 'deleted')
end
end
@ -127,7 +127,7 @@ module Importers
end
if migration.context.is_a?(Course)
imported_aq_ids = question_data[:aq_data].values.map { |aq| aq['assessment_question_id'] }.compact
imported_aq_ids = question_data[:aq_data].values.filter_map { |aq| aq['assessment_question_id'] }
imported_aq_ids.each_slice(100) do |sliced_aq_ids|
migration.context.quiz_questions.generated.where(:assessment_question_id => sliced_aq_ids).update_all(:assessment_question_version => nil)
end

View File

@ -31,7 +31,7 @@ module Importers
create_assignments(assignments, migration)
migration_ids = assignments.map { |m| m['assignment_id'] }.compact
migration_ids = assignments.filter_map { |m| m['assignment_id'] }
conn = Assignment.connection
cases = []
max = migration.context.assignments.pluck(:position).compact.max || 0

View File

@ -26,7 +26,7 @@ class KalturaMediaFileHandler
client = CanvasKaltura::ClientV3.new
client.startSession(CanvasKaltura::SessionType::ADMIN)
files = []
root_account_id = attachments.map(&:root_account_id).compact.first
root_account_id = attachments.filter_map(&:root_account_id).first
attachments.select { |a| !a.media_object }.each do |attachment|
files << {
:name => attachment.display_name,

View File

@ -94,7 +94,7 @@ module Lti
.current
.where(course_id: @canvas_context)
.preload(:associated_user)
.map { |e| e.try(:associated_user).try(:lti_context_id) }.compact
.filter_map { |e| e.try(:associated_user).try(:lti_context_id) }
end
def current_account_enrollments()

View File

@ -24,9 +24,9 @@ module OutcomesService
end
def learning_outcomes(context)
@migration.imported_migration_items_by_class(LearningOutcome).map do |item|
@migration.imported_migration_items_by_class(LearningOutcome).filter_map do |item|
outcome_attributes(item) if item.context == context
end.compact
end
end
def learning_outcome_groups(context)
@ -36,9 +36,9 @@ module OutcomesService
end
def learning_outcome_links
@migration.imported_migration_items_by_class(ContentTag).map do |item|
@migration.imported_migration_items_by_class(ContentTag).filter_map do |item|
link_attributes(item) if valid_link?(item)
end.compact
end
end
private

View File

@ -173,7 +173,7 @@ module OutcomesService
def export_artifacts(course, opts)
page_ids = if opts[:selective]
opts[:exported_assets].map { |asset| (match = asset.match(/wiki_page_(\d+)/)) && match[1] }.compact
opts[:exported_assets].filter_map { |asset| (match = asset.match(/wiki_page_(\d+)/)) && match[1] }
else
course.wiki_pages.pluck(:id)
end

View File

@ -84,11 +84,11 @@ module Quizzes::LogAuditing
def extract_answers(submission_data, quiz_data)
quiz_questions = begin
quiz_question_ids = submission_data.keys.map do |key|
quiz_question_ids = submission_data.keys.filter_map do |key|
if key =~ RE_QUESTION_ANSWER_FIELD
$1
end
end.compact.uniq
end.uniq
quiz_data.select do |qq|
quiz_question_ids.include?(qq['id'].to_s)

View File

@ -1332,7 +1332,7 @@ class Quizzes::Quiz < ActiveRecord::Base
def self.preload_can_unpublish(quizzes, assmnt_ids_with_subs = nil)
return unless quizzes.any?
assmnt_ids_with_subs ||= Assignment.assignment_ids_with_submissions(quizzes.map(&:assignment_id).compact)
assmnt_ids_with_subs ||= Assignment.assignment_ids_with_submissions(quizzes.filter_map(&:assignment_id))
# yes, this is a complicated query, but it greatly improves the runtime to do it this way
filter = Quizzes::QuizSubmission.where("quiz_submissions.quiz_id=s.quiz_id")

View File

@ -74,7 +74,7 @@ class Quizzes::QuizQuestion < ActiveRecord::Base
def infer_defaults
if !self.position && self.quiz
self.position = if self.quiz_group
(self.quiz_group.quiz_questions.active.map(&:position).compact.max || 0) + 1
(self.quiz_group.quiz_questions.active.filter_map(&:position).max || 0) + 1
else
self.quiz.root_entries_max_position + 1
end

View File

@ -32,7 +32,7 @@ class Quizzes::QuizStatistics::ItemAnalysis::Summary
user_ids = Enrollment.active.where(course_section_id: param_options[:section_ids], course_id: quiz.context).distinct.pluck(:user_id)
attempts_query = attempts_query.where(user_id: user_ids)
end
@attempts = attempts_query.map { |qs| qs.submitted_attempts.first }.compact
@attempts = attempts_query.filter_map { |qs| qs.submitted_attempts.first }
@options = options
@options[:buckets] ||= [
[:top, 0.73],

View File

@ -281,13 +281,13 @@ class Quizzes::QuizStatistics::StudentAnalysis < Quizzes::QuizStatistics::Report
case question[:question_type]
when 'fill_in_multiple_blanks_question'
blank_ids = question[:answers].map { |a| a[:blank_id] }.uniq
row << blank_ids.map { |blank_id| answer["answer_for_#{blank_id}".to_sym].try(:gsub, /,/, '\,') }.compact.join(',')
row << blank_ids.filter_map { |blank_id| answer["answer_for_#{blank_id}".to_sym].try(:gsub, /,/, '\,') }.join(',')
when 'multiple_answers_question'
row << question[:answers].map { |a| answer["answer_#{a[:id]}".to_sym] == '1' ? a[:text].gsub(/,/, '\,') : nil }.compact.join(',')
row << question[:answers].filter_map { |a| answer["answer_#{a[:id]}".to_sym] == '1' ? a[:text].gsub(/,/, '\,') : nil }.join(',')
when 'multiple_dropdowns_question'
blank_ids = question[:answers].map { |a| a[:blank_id] }.uniq
answer_ids = blank_ids.map { |blank_id| answer["answer_for_#{blank_id}".to_sym] }
row << answer_ids.map { |answer_id| (question[:answers].detect { |a| a[:id] == answer_id } || {})[:text].try(:gsub, /,/, '\,') }.compact.join(',')
row << answer_ids.filter_map { |answer_id| (question[:answers].detect { |a| a[:id] == answer_id } || {})[:text].try(:gsub, /,/, '\,') }.join(',')
when 'calculated_question'
list = question[:answers].take(1).flat_map do |ans|
ans[:variables]&.map do |variable|

View File

@ -276,7 +276,7 @@ class Quizzes::QuizSubmission < ActiveRecord::Base
end
def points_possible_at_submission_time
self.questions.map { |q| q[:points_possible].to_f }.compact.sum || 0
self.questions.filter_map { |q| q[:points_possible].to_f }.sum || 0
end
def questions
@ -377,7 +377,7 @@ class Quizzes::QuizSubmission < ActiveRecord::Base
end
def quiz_question_ids
questions.map { |question| question["id"] }.compact
questions.filter_map { |question| question["id"] }
end
def quiz_questions

View File

@ -78,7 +78,7 @@ class Quizzes::QuizSubmissionZipper < ContentZipper
# TODO: Refactor me! This pattern is also used for Student Analysis CSVs.
def find_attachments
ids = submissions.map(&:submission_data).compact.flatten.select do |submission|
ids = submissions.filter_map(&:submission_data).flatten.select do |submission|
submission[:attachment_ids].present?
end.map do |submission|
submission[:attachment_ids]
@ -97,7 +97,7 @@ class Quizzes::QuizSubmissionZipper < ContentZipper
).pluck(:user_id)
submissions = submissions.where(:user_id => visible_student_ids)
end
@submissions = submissions.reject(&:was_preview).map(&:latest_submitted_attempt).compact
@submissions = submissions.reject(&:was_preview).filter_map(&:latest_submitted_attempt)
end
def quiz_zip_filename(quiz)

View File

@ -112,7 +112,7 @@ module Quizzes
return unless @submission.user_id
versioned_submission = versioned_submission(@submission, attempt)
question_ids = (versioned_submission&.quiz_data || []).map { |q| q[:assessment_question_id] }.compact.uniq
question_ids = (versioned_submission&.quiz_data || []).filter_map { |q| q[:assessment_question_id] }.uniq
questions, alignments = questions_and_alignments(question_ids)
return if questions.empty? || alignments.empty?

View File

@ -26,7 +26,7 @@ module QuizzesNext
def begin_export(course, opts)
selected_assignment_ids = nil
if opts[:selective]
selected_assignment_ids = opts[:exported_assets].map { |asset| (match = asset.match(/assignment_(\d+)/)) && match[1] }.compact
selected_assignment_ids = opts[:exported_assets].filter_map { |asset| (match = asset.match(/assignment_(\d+)/)) && match[1] }
return unless selected_assignment_ids.any?
end
assignments = QuizzesNext::Service.active_lti_assignments_for_course(course, selected_assignment_ids: selected_assignment_ids)

View File

@ -205,7 +205,7 @@ class Rubric < ActiveRecord::Base
end
def data_outcome_ids
(data || []).map { |c| c[:learning_outcome_id] }.compact.map(&:to_i).uniq
(data || []).filter_map { |c| c[:learning_outcome_id] }.map(&:to_i).uniq
end
def criteria_object

View File

@ -47,7 +47,7 @@ class RubricAssessment < ActiveRecord::Base
after_save :track_outcomes
def track_outcomes
outcome_ids = (self.data || []).map { |r| r[:learning_outcome_id] }.compact.uniq
outcome_ids = (self.data || []).filter_map { |r| r[:learning_outcome_id] }.uniq
peer_review = self.assessment_type == "peer_review"
provisional_grade = self.artifact_type == "ModeratedGrading::ProvisionalGrade"
update_outcomes = outcome_ids.present? && !peer_review && !provisional_grade

View File

@ -39,7 +39,7 @@ class SubmissionVersion < ActiveRecord::Base
end
def index_versions(versions, options = {})
records = versions.map { |version| extract_version_attributes(version, options) }.compact
records = versions.filter_map { |version| extract_version_attributes(version, options) }
bulk_insert(records) if records.present?
end

View File

@ -1600,14 +1600,14 @@ class User < ActiveRecord::Base
if Shard.current != self.shard
# translate asset strings to be relative to current shard
colors_hash = Hash[
colors_hash.map do |asset_string, value|
colors_hash.filter_map do |asset_string, value|
opts = asset_string.split("_")
id_relative_to_user_shard = opts.pop.to_i
next if id_relative_to_user_shard > Shard::IDS_PER_SHARD && Shard.shard_for(id_relative_to_user_shard) == self.shard # this is old data and should be ignored
new_id = Shard.relative_id_for(id_relative_to_user_shard, self.shard, Shard.current)
["#{opts.join('_')}_#{new_id}", value]
end.compact
end
]
end
colors_hash
@ -2236,7 +2236,7 @@ class User < ActiveRecord::Base
visible_instances = visible_stream_item_instances(opts)
.preload(stream_item: :context)
.limit(Setting.get('recent_stream_item_limit', 100))
visible_instances.map do |sii|
visible_instances.filter_map do |sii|
si = sii.stream_item
next if si.blank?
next if si.asset_type == 'Submission'
@ -2244,7 +2244,7 @@ class User < ActiveRecord::Base
si.unread = sii.unread?
si
end.compact
end
end
end
end

View File

@ -52,7 +52,7 @@ class UserPastLtiId < ActiveRecord::Base
# user_merge, but we still want to avoid the N+1
def self.manual_preload_past_lti_ids(objects, object_context)
# collaborators are allowed to not have a user, so we compact them here.
users = objects.first.is_a?(User) ? objects : objects.map(&:user).compact
users = objects.first.is_a?(User) ? objects : objects.filter_map(&:user)
past_lti_ids = UserPastLtiId.where(user_id: users, context: object_context).group_by(&:user_id)
users.each do |user|
past_lti_id = past_lti_ids[user.id]

View File

@ -551,7 +551,7 @@ class WebConference < ActiveRecord::Base
end
def self.plugin_types
plugins.map { |plugin|
plugins.filter_map { |plugin|
next unless plugin.enabled? &&
(klass = (plugin.base || "#{plugin.id.classify}Conference").constantize rescue nil) &&
klass < self.base_class
@ -563,7 +563,7 @@ class WebConference < ActiveRecord::Base
:name => plugin.name,
:plugin => plugin
).with_indifferent_access
}.compact
}
end
def self.config(context: nil, class_name: nil)

View File

@ -32,13 +32,13 @@ class AuthenticationProvidersPresenter
end
def new_auth_types
AuthenticationProvider.valid_auth_types.map do |auth_type|
AuthenticationProvider.valid_auth_types.filter_map do |auth_type|
klass = AuthenticationProvider.find_sti_class(auth_type)
next unless klass.enabled?(account)
next if klass.singleton? && configs.any? { |aac| aac.is_a?(klass) }
klass
end.compact
end
end
def needs_unknown_user_url?

View File

@ -36,9 +36,9 @@ class ToDoListPresenter
@needs_submitting.sort_by! { |a| a.due_at || a.updated_at }
assessment_requests = user.submissions_needing_peer_review(contexts: contexts, limit: ASSIGNMENT_LIMIT)
@needs_reviewing = assessment_requests.map do |ar|
@needs_reviewing = assessment_requests.filter_map do |ar|
AssessmentRequestPresenter.new(view, ar, user) if ar.asset.assignment.published?
end.compact
end
# we need a complete list of courses first because we only care about the courses
# from the assignments involved. not just the contexts handed in.

View File

@ -86,12 +86,12 @@ class DockerfileWriter
end
def docker_compose_volume_paths
paths = (docker_compose_config["services"]["web"]["volumes"] || []).map do |volume|
paths = (docker_compose_config["services"]["web"]["volumes"] || []).filter_map do |volume|
name, path = volume.split(":")
next unless /\A[a-z]/.match?(name)
path.sub("/usr/src/app/", "")
end.compact
end
paths.sort_by { |path| [path[0] == "/" ? 1 : 0, path] }
end

View File

@ -23,8 +23,8 @@ class Gergich::XSSLint
# e.g. alerts.js:110: possibly XSS-able argument to `append()`
pattern = /^([^:\n]+):(\d+): (.*)$/
output.scan(pattern).map { |file, line, error|
output.scan(pattern).filter_map { |file, line, error|
{ path: file, message: "[xsslint] #{error}", position: line.to_i, severity: "error" }
}.compact
}
end
end

View File

@ -114,8 +114,8 @@ class ActiveRecord::Base
def self.find_all_by_asset_string(strings, asset_types = nil)
assets = strings.is_a?(Hash) ? strings : parse_asset_string_list(strings)
assets.map do |klass, ids|
next if asset_types && asset_types.exclude?(klass)
assets.filter_map do |klass, ids|
next if asset_types&.exclude?(klass)
begin
klass = klass.constantize
@ -125,7 +125,7 @@ class ActiveRecord::Base
next unless klass < ActiveRecord::Base
klass.where(id: ids).to_a
end.compact.flatten
end.flatten
end
# takes an asset string list, like "course_5,user_7,course_9" and turns it into an
@ -1804,12 +1804,12 @@ ActiveModel::AttributeMutationTracker.prepend(DupArraysInMutationTracker)
module IgnoreOutOfSequenceMigrationDates
def current_migration_number(dirname)
migration_lookup_at(dirname).map do |file|
migration_lookup_at(dirname).filter_map do |file|
digits = File.basename(file).split("_").first
next if ActiveRecord::Base.timestamped_migrations && digits.length != 14
digits.to_i
end.compact.max.to_i
end.max.to_i
end
end
# Thor doesn't call `super` in its `inherited` method, so hook in so that we can hook in later :)

View File

@ -142,7 +142,7 @@ Rails.application.config.after_initialize do
Switchman::DatabaseServer.class_eval do
def self.regions
@regions ||= all.map { |db| db.config[:region] }.compact.uniq.sort
@regions ||= all.filter_map { |db| db.config[:region] }.uniq.sort
end
def in_region?(region)

View File

@ -94,7 +94,7 @@ class RegisterExpansionHandler < YARD::Handlers::Ruby::Base
end
def availability
all_availabilities = all_guards.map do |guard|
all_availabilities = all_guards.filter_map do |guard|
case guard
when 'ALWAYS', 'CONTROLLER_GUARD'
"always"
@ -133,7 +133,7 @@ class RegisterExpansionHandler < YARD::Handlers::Ruby::Base
when 'FILE_UPLOAD_GUARD'
"when the tool is used to upload a file as an assignment submission"
end
end.compact
end
"**Availability**: *#{all_availabilities.join(' and ')}* " if all_availabilities.size
end
end

View File

@ -215,14 +215,14 @@ module CanvasHttp
raise UnresolvableUriError, "#{host} cannot be resolved to any address"
end
ip_addrs = resolved_addrs.map do |ip|
ip_addrs = resolved_addrs.filter_map do |ip|
::IPAddr.new(ip)
rescue IPAddr::InvalidAddressError
# this should never happen, Resolv should only be passing back IPs, but
# let's make sure we can see if the impossible occurs
logger.warn("CANVAS_HTTP WARNING | host: #{host} | invalid_ip: #{ip}")
nil
end.compact
end
unless ip_addrs.any?
raise UnresolvableUriError, "#{host} resolves to only unparseable IPs..."
end

View File

@ -119,7 +119,7 @@ module CanvasPartman
else
[reflection.klass]
end
klasses.map { |klass| klass.maximum(klass.primary_key) }.compact.max
klasses.filter_map { |klass| klass.maximum(klass.primary_key) }.max
end
def table_regex

View File

@ -36,7 +36,7 @@ module AcademicBenchmarks
vendor_guid: guid,
is_global_standard: true,
type: 'learning_outcome_group',
outcomes: children.map { |c| c.build_outcomes(ratings, self) }.compact
outcomes: children.filter_map { |c| c.build_outcomes(ratings, self) }
}
end
end

View File

@ -91,7 +91,7 @@ module AccountReports
students = student_grade_scope.where(course_id: runner.batch_items)
students.preload(:root_account, :sis_pseudonym).find_in_batches do |student_chunk|
users = student_chunk.map { |e| User.new(id: e.user_id) }.compact
users = student_chunk.filter_map { |e| User.new(id: e.user_id) }
users.uniq!
users_by_id = users.index_by(&:id)
courses_by_id = Course.where(id: student_chunk.map(&:course_id)).preload(:grading_standard).index_by(&:id)
@ -201,7 +201,7 @@ module AccountReports
students = student_grade_scope.where(course_id: runner.batch_items)
courses_by_id = Course.where(id: runner.batch_items).preload(:grading_standard).index_by(&:id)
students.where(course_id: runner.batch_items).preload(:root_account, :sis_pseudonym).find_in_batches do |student_chunk|
users = student_chunk.map { |e| User.new(id: e.user_id) }.compact
users = student_chunk.filter_map { |e| User.new(id: e.user_id) }
users.uniq!
users_by_id = users.index_by(&:id)
pseudonyms = preload_logins_for_users(users, include_deleted: @include_deleted)

View File

@ -494,8 +494,8 @@ module AccountReports
# because it often is big enough that the secondary
# kills it mid-run (http://www.postgresql.org/docs/9.0/static/hot-standby.html)
enrol.preload(:root_account, :sis_pseudonym, :role).find_in_batches(strategy: :id) do |batch|
users = batch.map { |e| User.new(id: e.user_id) }.compact
users += batch.map { |e| User.new(id: e.associated_user_id) unless e.associated_user_id.nil? }.compact
users = batch.filter_map { |e| User.new(id: e.user_id) }
users += batch.filter_map { |e| User.new(id: e.associated_user_id) unless e.associated_user_id.nil? }
users.uniq!
users_by_id = users.index_by(&:id)
pseudonyms = preload_logins_for_users(users, include_deleted: @include_deleted)
@ -791,7 +791,7 @@ module AccountReports
generate_and_run_report headers do |csv|
gm.find_in_batches do |batch|
users = batch.map { |au| User.new(id: au.user_id) }.compact.uniq
users = batch.filter_map { |au| User.new(id: au.user_id) }.uniq
users_by_id = users.index_by(&:id)
sis_ids = preload_logins_for_users(users, include_deleted: @include_deleted)
@ -973,7 +973,7 @@ module AccountReports
admins = admin_query_options(admins)
generate_and_run_report headers do |csv|
admins.find_in_batches do |batch|
users = batch.map { |au| User.new(id: au.user_id) }.compact.uniq
users = batch.filter_map { |au| User.new(id: au.user_id) }.uniq
users_by_id = users.index_by(&:id)
sis_ids = preload_logins_for_users(users, include_deleted: @include_deleted)

View File

@ -82,7 +82,7 @@ module ReportSpecHelper
header = all_parsed.shift
if all_parsed.present? && !skip_order
# cast any numbery looking things so we sort them intuitively
type_casts = order.map { |k| /\A\d+(\.\d+)?\z/.match?(all_parsed.map { |row| row[k] }.compact.first) ? :to_f : :to_s }
type_casts = order.map { |k| /\A\d+(\.\d+)?\z/.match?(all_parsed.filter_map { |row| row[k] }.first) ? :to_f : :to_s }
all_parsed.sort_by! { |r| r.values_at(*order).each_with_index.map { |v, i| v.send type_casts[i] } }
end
all_parsed.unshift(header) if options[:header]

View File

@ -63,7 +63,7 @@ module ActiveRecord
multi_key_types, key_types = key_types.partition { |type| Canvas::CacheRegister.can_use_multi_cache_redis? && self.prefer_multi_cache_for_key_type?(type) }
::Shard.partition_by_shard(Array(ids_or_records)) do |sharded_ids_or_records|
base_keys = sharded_ids_or_records.map { |item| base_cache_register_key_for(item) }.compact
base_keys = sharded_ids_or_records.filter_map { |item| base_cache_register_key_for(item) }
next if base_keys.empty?
if key_types.any?

View File

@ -89,7 +89,7 @@ module AddressBook
@cache.null(uncached)
# implementation is responsible for storing known users into cache
super(uncached, options)
users.map { |user| @cache.fetch(user) }.compact
users.filter_map { |user| @cache.fetch(user) }
end
end
end

View File

@ -156,7 +156,7 @@ module AddressBook
ids = ids.map { |id| Shard.global_id_for(id) }
hydrated = User.select(::MessageableUser::SELECT).where(id: ids)
reverse_lookup = hydrated.index_by(&:global_id)
ids.map { |id| reverse_lookup[id] }.compact
ids.filter_map { |id| reverse_lookup[id] }
end
# caches with common contexts for each user in the list, pulling the

View File

@ -232,7 +232,7 @@ module Api::V1::Attachment
end
def filenames(params)
[:name, :filename, :url].map { |param| params[param] }.compact
[:name, :filename, :url].filter_map { |param| params[param] }
end
def valid_mime_type?(mime_type)
@ -240,10 +240,10 @@ module Api::V1::Attachment
end
def valid_mime_types(params)
filenames(params).map do |filename|
filenames(params).filter_map do |filename|
mime_type = Attachment.mimetype(filename)
mime_type if valid_mime_type?(mime_type)
end.compact
end
end
def validate_on_duplicate(params)

View File

@ -81,7 +81,7 @@ module Api::V1::AuthenticationEvent
User.where(:id => shard_user_ids).to_a
end
page_view_ids = events.map(&:request_id).compact
page_view_ids = events.filter_map(&:request_id)
page_views = PageView.find_all_by_id(page_view_ids) if page_view_ids.length > 0
page_views ||= []

View File

@ -128,7 +128,7 @@ module Api::V1::CalendarEvent
participant = context.participant_for(user)
participant_child_events = event.child_events_for(participant)
hash['reserved'] = (Array === participant_child_events ? participant_child_events.present? : participant_child_events.exists?)
hash['reserve_comments'] = participant_child_events.map(&:comments).compact.join(", ")
hash['reserve_comments'] = participant_child_events.filter_map(&:comments).join(", ")
hash['reserve_url'] = api_v1_calendar_event_reserve_url(event, participant)
else
hash['reserve_url'] = api_v1_calendar_event_reserve_url(event, '{{ id }}')

View File

@ -81,7 +81,7 @@ module Api::V1::ContentShare
def get_content_type_from_export_settings(settings)
return nil unless settings.key?('selected_content')
selected_types = settings['selected_content'].keys.map { |k| EXPORT_TYPES[k] }.compact
selected_types = settings['selected_content'].keys.filter_map { |k| EXPORT_TYPES[k] }
%w(module module_item).each { |k| return k if selected_types.include?(k) }
# otherwise there should be only one selected type...
selected_types.first

View File

@ -81,18 +81,18 @@ module Api::V1::CourseEvent
end
def linked_json(events, user, session)
course_ids = events.map(&:course_id).compact
course_ids.concat(events.map do |event|
course_ids = events.filter_map(&:course_id)
course_ids.concat(events.filter_map do |event|
event.event_data[event.event_type] if event.event_data
end.compact)
end)
courses = Course.where(id: course_ids).to_a if course_ids.length > 0
courses ||= []
page_view_ids = events.map(&:request_id).compact
page_view_ids = events.filter_map(&:request_id)
page_views = PageView.find_all_by_id(page_view_ids) if page_view_ids.length > 0
page_views ||= []
user_ids = events.map(&:user_id).compact
user_ids = events.filter_map(&:user_id)
users = User.where(id: user_ids).to_a if user_ids.length > 0
users ||= []

View File

@ -83,20 +83,20 @@ module Api::V1::GradeChangeEvent
end
def linked_json(events, user, session)
course_ids = events.map(&:course_id).compact
course_ids = events.filter_map(&:course_id)
courses = Course.where(id: course_ids).to_a if course_ids.length > 0
courses ||= []
assignment_ids = events.map(&:assignment_id).compact
assignment_ids = events.filter_map(&:assignment_id)
assignments = Assignment.where(id: assignment_ids).to_a if assignment_ids.length > 0
assignments ||= []
user_ids = events.map(&:grader_id).compact
user_ids.concat(events.map(&:student_id).compact)
user_ids = events.filter_map(&:grader_id)
user_ids.concat(events.filter_map(&:student_id))
users = User.where(id: user_ids).to_a if user_ids.length > 0
users ||= []
page_view_ids = events.map(&:request_id).compact
page_view_ids = events.filter_map(&:request_id)
page_views = PageView.find_all_by_id(page_view_ids) if page_view_ids.length > 0
page_views ||= []

View File

@ -126,7 +126,7 @@ module Api::V1::QuizSubmission
end
def quiz_submission_zip(quiz)
latest_submission = quiz.quiz_submissions.map(&:finished_at).compact.max
latest_submission = quiz.quiz_submissions.filter_map(&:finished_at).max
submission_zip(quiz, latest_submission)
end
end

View File

@ -99,7 +99,7 @@ module Api::V1::SisAssignment
overrides = active_assignment_overrides_for(assignment)
raise UnloadedAssociationError if overrides.nil?
overrides.map { |o| assignment_user_override_json(o) }.compact
overrides.filter_map { |o| assignment_user_override_json(o) }
end
def assignment_user_override_json(override)

View File

@ -209,7 +209,7 @@ module Api::V1::Submission
if other_fields.include?('attachments')
attachments = attempt.versioned_attachments.dup
attachments << attempt.attachment if attempt.attachment && attempt.attachment.context_type == 'Submission' && attempt.attachment.context_id == attempt.id
hash['attachments'] = attachments.map do |attachment|
hash['attachments'] = attachments.filter_map do |attachment|
includes = includes.include?('canvadoc_document_id') ? ['preview_url', 'canvadoc_document_id'] : ['preview_url']
options = {
anonymous_instructor_annotations: assignment.anonymous_instructor_annotations?,
@ -222,7 +222,7 @@ module Api::V1::Submission
}
attachment_json(attachment, user, {}, options)
end.compact unless attachments.blank?
end unless attachments.blank?
end
# include the discussion topic entries

View File

@ -116,7 +116,7 @@ module Api::V1::User
if includes.include?('sections')
json[:sections] = user.enrollments
.map(&:course_section).compact.uniq
.filter_map(&:course_section).uniq
.map(&:name).join(", ")
end

View File

@ -70,7 +70,7 @@ module Canvas
@last_clear_time = Time.now.utc
# gather all the redises we can find
redises = Switchman.config[:cache_map].values
.map { |cache| cache.try(:redis) }.compact.uniq
.filter_map { |cache| cache.try(:redis) }.uniq
.map { |redis| redis.try(:ring)&.nodes || [redis] }.inject([], &:concat).uniq
redises.each { |r| r._client.disconnect_if_idle(@last_clear_time - clear_timeout) }
end

View File

@ -222,7 +222,7 @@ class GradeCalculator
end
def compute_scores_and_group_sums_for_batch(user_ids)
user_ids.map do |user_id|
user_ids.filter_map do |user_id|
next unless enrollments_by_user[user_id].first
group_sums = compute_group_sums_for_user(user_id)
@ -234,7 +234,7 @@ class GradeCalculator
final: scores[:final],
final_groups: group_sums[:final].index_by { |group| group[:id] }
}
end.compact
end
end
def assignment_visible_to_student?(assignment_id, user_id)
@ -803,7 +803,7 @@ class GradeCalculator
Rails.logger.debug "GRADES: calculating... submissions=#{logged_submissions.inspect}"
kept = drop_assignments(group_submissions, group.rules_hash)
dropped_submissions = (group_submissions - kept).map { |s| s[:submission]&.id }.compact
dropped_submissions = (group_submissions - kept).filter_map { |s| s[:submission]&.id }
score, possible = kept.reduce([0.0, 0.0]) { |(s_sum, p_sum), s|
[s_sum.to_d + s[:score].to_d, p_sum.to_d + s[:total].to_d]

View File

@ -461,7 +461,7 @@ class GradebookImporter
# this method requires non-assignment columns to be stripped from the row
def parse_assignments(stripped_row)
stripped_row.map do |name_and_id|
stripped_row.filter_map do |name_and_id|
title, id = Assignment.title_and_id(name_and_id)
assignment = @all_assignments[id.to_i] if id.present?
# backward compat
@ -474,7 +474,7 @@ class GradebookImporter
@missing_assignment ||= assignment.new_record?
{ assignment: assignment, header_name: name_and_id } if assignment
end.compact
end
end
def detect_override_columns(row)
@ -629,7 +629,7 @@ class GradebookImporter
@gradebook_importer_override_scores.each_value do |changes_for_student|
includes_course_scores ||= changes_for_student.any?(&:course_score?)
grading_period_ids = grading_period_ids.merge(changes_for_student.map(&:grading_period_id).compact)
grading_period_ids = grading_period_ids.merge(changes_for_student.filter_map(&:grading_period_id))
end
{

View File

@ -37,7 +37,7 @@ module Lti
end
def app_definitions(collection, opts = {})
collection.map do |o|
collection.filter_map do |o|
case o
when ContextExternalTool
hash = external_tool_definition(o)
@ -48,7 +48,7 @@ module Lti
when ToolProxy
tool_proxy_definition(o)
end
end.compact
end
end
private

View File

@ -217,9 +217,9 @@ module Lti
params[:accept_copy_advice] = !!assignment.submission_types.include?('online_upload')
if assignment.submission_types.strip == 'online_upload' && assignment.allowed_extensions.present?
params[:ext_content_file_extensions] = assignment.allowed_extensions.compact.join(',')
params[:accept_media_types] = assignment.allowed_extensions.map do |ext|
params[:accept_media_types] = assignment.allowed_extensions.filter_map do |ext|
MimetypeFu::EXTENSIONS[ext]
end.compact.join(',')
end.join(',')
end
params
end

View File

@ -38,7 +38,7 @@ module Lti
else
user.not_ended_enrollments.where(course: context)
end
enrollments.map do |enrollment|
enrollments.filter_map do |enrollment|
case enrollment.type
when 'TeacherEnrollment'
::IMS::LIS::Roles::Context::URNs::Instructor
@ -51,7 +51,7 @@ module Lti
when 'ObserverEnrollment'
::IMS::LIS::Roles::Context::URNs::Learner_NonCreditLearner
end
end.compact.uniq
end.uniq
end
end
end

View File

@ -202,7 +202,7 @@ module Lti::Messages
@_current_observee_list ||= @user.observer_enrollments.current
.where(course_id: @context.id)
.preload(:associated_user)
.map { |e| e.try(:associated_user).try(:lti_id) }.compact
.filter_map { |e| e.try(:associated_user).try(:lti_id) }
end
def custom_parameters

View File

@ -215,7 +215,7 @@ module Lti
end
def previous_lti_context_ids
previous_course_ids_and_context_ids.map(&:last).compact.join(',')
previous_course_ids_and_context_ids.filter_map(&:last).join(',')
end
def previous_course_ids
@ -231,7 +231,7 @@ module Lti
end
def section_sis_ids
course_sections.map(&:sis_source_id).compact.uniq.sort.join(',')
course_sections.filter_map(&:sis_source_id).uniq.sort.join(',')
end
def sis_email

View File

@ -777,7 +777,7 @@ class MessageableUser
# is acceptable, as this is specific to a course and the enrollments all
# live on the same shard as the course
def uncached_observed_student_ids_in_course(course)
course.section_visibilities_for(@user).map { |s| s[:associated_user_id] }.compact
course.section_visibilities_for(@user).filter_map { |s| s[:associated_user_id] }
end
def uncached_linked_observer_ids

View File

@ -60,10 +60,10 @@ module MicrosoftSync
def initialize(msg, responses)
super(msg)
@retry_after_seconds = responses.map do |resp|
@retry_after_seconds = responses.filter_map do |resp|
headers = resp['headers']&.transform_keys(&:downcase) || {}
headers['retry-after'].presence&.to_f
end.compact.max
end.max
end
def self.public_message

View File

@ -97,7 +97,7 @@ module MicrosoftSync
private
def aads_with_action(action)
@user_infos.values.select { |info| info.actions.include?(action) }.map(&:aad_id).compact.uniq
@user_infos.values.select { |info| info.actions.include?(action) }.filter_map(&:aad_id).uniq
end
class UserInfo

View File

@ -68,7 +68,7 @@ module SendToStream
def generate_stream_items(stream_recipients)
@generated_stream_items ||= []
self.extend TextHelper
@stream_item_recipient_ids = stream_recipients.compact.map { |u| User.infer_id(u) }.compact.uniq
@stream_item_recipient_ids = stream_recipients.compact.filter_map { |u| User.infer_id(u) }.uniq
@generated_stream_items = StreamItem.generate_all(self, @stream_item_recipient_ids)
end

View File

@ -65,7 +65,7 @@ module SIS
ids_to_touch = (batch + UserObserver.where(user_id: batch).pluck(:observer_id)).uniq
User.touch_and_clear_cache_keys(ids_to_touch, :enrollments) if ids_to_touch.any?
end
i.enrollments_to_add_to_favorites.map(&:id).compact.each_slice(1000) do |sliced_ids|
i.enrollments_to_add_to_favorites.filter_map(&:id).each_slice(1000) do |sliced_ids|
Enrollment.delay(priority: Delayed::LOW_PRIORITY, strand: "batch_add_to_favorites_#{@root_account.global_id}")
.batch_add_to_favorites(sliced_ids)
end

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