RuboCop: Lint/UselessAssignment app, config, doc, gems, lib

(everything except spec)

all manual

Change-Id: I6c49a3139efb0f0802ba63a15cab4d4d2cd0b8dd
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/276310
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-10-19 15:23:50 -06:00
parent 19d9329411
commit 44614b47d7
108 changed files with 142 additions and 217 deletions

View File

@ -877,8 +877,7 @@ class AssignmentsApiController < ApplicationController
ActiveRecord::Associations::Preloader.new.preload(assignments, :score_statistic)
end
hashes = []
hashes = assignments.map do |assignment|
assignments.map do |assignment|
visibility_array = assignment_visibilities[assignment.id] if assignment_visibilities
submission = submissions[assignment.id]
needs_grading_course_proxy = @context.grants_right?(user, session, :manage_grades) ?
@ -897,7 +896,6 @@ class AssignmentsApiController < ApplicationController
include_can_edit: include_params.include?('can_edit'),
include_score_statistics: include_params.include?('score_statistics'))
end
hashes
end
end

View File

@ -530,7 +530,6 @@ class AssignmentsController < ApplicationController
def syllabus
rce_js_env
add_crumb @context.elementary_enabled? ? t("Important Info") : t('#crumbs.syllabus', "Syllabus")
active_tab = "Syllabus"
@course_home_sub_navigation_tools =
ContextExternalTool.all_tools_for(@context, placements: :course_home_sub_navigation,

View File

@ -506,7 +506,6 @@ class CalendarEventsApiController < ApplicationController
# Create duplicates if necessary
events = []
dup_options = get_duplicate_params(params[:calendar_event])
title = dup_options[:title]
if dup_options[:count] > 0
events += create_event_and_duplicates(dup_options)
else

View File

@ -51,7 +51,7 @@ class ContextModulesController < ApplicationController
collection_cache_key(@modules), Time.zone, Digest::MD5.hexdigest([visible_assignments, @section_visibility].join("/"))]
cache_key = cache_key_items.join('/')
cache_key = add_menu_tools_to_cache_key(cache_key)
cache_key = add_mastery_paths_to_cache_key(cache_key, @context, @current_user)
add_mastery_paths_to_cache_key(cache_key, @context, @current_user)
end
end

View File

@ -1529,8 +1529,6 @@ class CoursesController < ApplicationController
end
def update_user_engine_choice(course, selection_obj)
old_selection = course.settings[:engine_selected][:user_id]
new_settings = {}
new_selections = {}
new_selections[:user_id] = {
newquizzes_engine_selected: selection_obj[:newquizzes_engine_selected],
@ -1866,9 +1864,8 @@ class CoursesController < ApplicationController
if session[:accepted_enrollment_uuid].present? &&
(enrollment = @context.enrollments.where(uuid: session[:accepted_enrollment_uuid]).first)
success = false
if enrollment.invited?
success = enrollment.accept!
enrollment.accept!
flash[:notice] = t('notices.invitation_accepted', "Invitation accepted! Welcome to %{course}!", :course => @context.name)
end

View File

@ -163,7 +163,6 @@ class DiscussionTopicsApiController < ApplicationController
)
include_enrollment_state = params[:include_enrollment_state] && (@context.is_a?(Course) || @context.is_a?(Group)) &&
@context.grants_right?(@current_user, session, :read_as_admin)
enrollments = nil
if include_enrollment_state || include_context_card_info
enrollment_context = @context.is_a?(Course) ? @context : @context.context
all_enrollments = enrollment_context.enrollments.where(:user_id => participants).to_a

View File

@ -438,7 +438,6 @@ class DiscussionTopicsController < ApplicationController
add_body_class 'hide-content-while-scripts-not-loaded'
@page_title = join_title(t('#titles.discussions', "Discussions"), @context.name)
feed_code = @context_enrollment.try(:feed_code) || (@context.available? && @context.feed_code)
content_for_head helpers.auto_discovery_link_tag(:atom, feeds_forum_format_path(@context.feed_code, :atom), { :title => t(:course_discussions_atom_feed_title, "Course Discussions Atom Feed") })
js_bundle :discussion_topics_index

View File

@ -31,7 +31,6 @@ class EportfolioCategoriesController < ApplicationController
def create
if authorized_action(@portfolio, @current_user, :update)
category_names = @portfolio.eportfolio_categories.map { |c| c.name }
@category = @portfolio.eportfolio_categories.build(eportfolio_category_params)
respond_to do |format|
if @category.save

View File

@ -32,7 +32,6 @@ class EportfolioEntriesController < ApplicationController
if authorized_action(@portfolio, @current_user, :update)
@category = @portfolio.eportfolio_categories.find(params[:eportfolio_entry].delete(:eportfolio_category_id))
page_names = @category.eportfolio_entries.map { |c| c.name }
@page = @portfolio.eportfolio_entries.build(eportfolio_entry_params)
@page.eportfolio_category = @category
@page.parse_content(params)

View File

@ -498,7 +498,6 @@ class FilesController < ApplicationController
def show
GuardRail.activate(:secondary) do
original_params = params.dup
params[:id] ||= params[:file_id]
get_context
# note that the /files/XXX URL implicitly uses the current user as the

View File

@ -111,7 +111,7 @@ module Lti::Concerns
params.require(:oembed_token),
associated_tool.shared_secret
)
rescue JSON::JWS::VerificationFailed, JSON::JWS::UnexpectedAlgorithm => error
rescue JSON::JWS::VerificationFailed, JSON::JWS::UnexpectedAlgorithm
raise OembedAuthorizationError.new 'Error validating oembed_token signature'
end
end

View File

@ -52,7 +52,7 @@ class ObserverAlertThresholdsApiController < ApplicationController
return render json: { errors: ['user_id is invalid'] }, status: :bad_request
end
threshold = ObserverAlertThreshold.where(observer: @current_user, student: attrs[:user_id], alert_type: attrs[:alert_type]).take
threshold = ObserverAlertThreshold.where(observer: @current_user, student: user, alert_type: attrs[:alert_type]).take
if threshold
# update if duplicate
threshold.update(threshold: attrs[:threshold], workflow_state: 'active')

View File

@ -40,12 +40,9 @@ class OutcomeGroupsController < ApplicationController
if authorized_action(@context, @current_user, :manage_outcomes)
data = JSON.parse(params[:file].read).with_indifferent_access rescue nil
if data && data[:category] && data[:title] && data[:description] && data[:outcomes]
params = {}
group = @context.learning_outcome_groups.create(params)
group = @context.learning_outcome_groups.create
data[:outcomes].each do |outcome_hash|
params = {}
outcome_hash = outcome_hash.with_indifferent_access
group.learning_outcomes.create(params)
group.learning_outcomes.create
end
render :json => group.as_json(:include => :learning_outcomes),
:as_text => true

View File

@ -60,7 +60,7 @@ class OutcomesAcademicBenchmarkImportApiController < ApplicationController
cmj = content_migration_json(cm, @current_user, session)
cmj[:migration_issues] = migration_issues_json(cm_issues, cm, @current_user, session)
render json: cmj
rescue ActiveRecord::RecordNotFound => e
rescue ActiveRecord::RecordNotFound
render json: { error: "no content migration matching id #{params[:migration_id]}" }
end
end

View File

@ -315,7 +315,6 @@ class Quizzes::QuizzesController < ApplicationController
@quiz.due_at = params[:due_at] if params[:due_at]
@quiz.assignment_group_id = params[:assignment_group_id] if params[:assignment_group_id]
student_ids = @context.student_ids
@banks_hash = get_banks(@quiz)
if (@has_student_submissions = @quiz.has_student_submissions?)
@ -437,7 +436,6 @@ class Quizzes::QuizzesController < ApplicationController
end
def update
n = Time.now.to_f
if authorized_action(@quiz, @current_user, :update)
quiz_params = get_quiz_params
params[:quiz] ||= {}

View File

@ -131,7 +131,7 @@ class ReleaseNotesController < ApplicationController
end
end
notes = all_notes.sort_by { |note| note.show_ats[release_note_env] }.reverse!.first(latest_limit)
all_notes.sort_by { |note| note.show_ats[release_note_env] }.reverse!.first(latest_limit)
end
def last_seen_release_note

View File

@ -50,7 +50,7 @@ class RubricsController < ApplicationController
permission = @context.is_a?(User) ? :manage : [:manage_rubrics, :read_rubrics]
return unless authorized_action(@context, @current_user, permission)
if (id = params[:id]) =~ Api::ID_REGEX
if params[:id].match?(Api::ID_REGEX)
js_env :ROOT_OUTCOME_GROUP => get_root_outcome,
:PERMISSIONS => {
manage_rubrics: @context.grants_right?(@current_user, session, :manage_rubrics)

View File

@ -157,15 +157,15 @@ class UsageRightsController < ApplicationController
# recursively enumerate file ids under a folder
def enumerate_contents(folder)
ids = folder.active_sub_folders.inject([]) { |file_ids, folder| file_ids += enumerate_contents(folder) }
ids += folder.active_file_attachments.pluck(:id)
ids = folder.active_sub_folders.flat_map { |sub_folder| enumerate_contents(sub_folder) }
ids + folder.active_file_attachments.pluck(:id)
end
# assign the given usage rights to params[:file_ids] / params[:folder_ids]
def assign_usage_rights(usage_rights)
folder_ids = Array(params[:folder_ids]).map(&:to_i)
folders = @context.folders.active.where(id: folder_ids).to_a
file_ids = folders.inject([]) { |file_ids, folder| file_ids += enumerate_contents(folder) }
file_ids = folders.flat_map { |folder| enumerate_contents(folder) }
file_ids += @context.attachments.not_deleted.where(id: Array(params[:file_ids]).map(&:to_i)).pluck(:id)
update_attrs = { usage_rights_id: usage_rights&.id }
update_attrs.merge!(locked: false) if usage_rights.present? && value_to_boolean(params[:publish])

View File

@ -107,22 +107,20 @@ module ApplicationHelper
name = name.sub(/context/, context_name)
opts.unshift context.id
opts.push({}) unless opts[-1].is_a?(Hash)
ajax =
begin
opts[-1].delete :ajax
rescue StandardError
nil
end
begin
opts[-1].delete :ajax
rescue
nil
end
opts[-1][:only_path] = true unless opts[-1][:only_path] == false
res = self.send name, *opts
elsif opts[0].is_a? Hash
opts = opts[0]
ajax =
begin
opts[0].delete :ajax
rescue StandardError
nil
end
begin
opts[0].delete :ajax
rescue
nil
end
opts[:only_path] = true
opts["#{context_name}_id"] = context.id
res = self.url_for opts

View File

@ -31,7 +31,7 @@ module AvatarHelper
avatar_settings = (@domain_root_account && @domain_root_account.settings[:avatars]) || 'enabled'
user_id = Shard.global_id_for(user_id)
user_shard = Shard.shard_for(user_id)
image_url, alt_tag = user_shard.activate do
user_shard.activate do
Rails.cache.fetch(Cacher.inline_avatar_cache_key(user_id, avatar_settings)) do
if !user && user_id.to_i > 0
user ||= User.find(user_id)

View File

@ -55,7 +55,7 @@ module BrokenLinkHelper
course_validator = CourseLinkValidator.new(course)
course_validator.check_object_status(url, object: link_obj) || response_code_type
rescue => e
rescue
:missing_item
end

View File

@ -34,7 +34,7 @@ module CalendarConferencesHelper
end
end
elsif conference_params[:title].present?
conference = context.web_conferences.build(valid_params).tap do |conf|
context.web_conferences.build(valid_params).tap do |conf|
conf.user = @current_user
conf.settings[:default_return_url] = named_context_url(context, :context_url, :include_host => true)
end

View File

@ -663,7 +663,7 @@ module QuizzesHelper
end
titles = titles.map { |title| h(title) }
title = "title=\"#{titles.join(' ')}\"".html_safe if titles.length > 0
"title=\"#{titles.join(' ')}\"".html_safe if titles.length > 0 # rubocop:disable Rails/OutputSafety
end
def matching_answer_title(item_text, did_select_answer, selected_answer_text, is_correct_answer, correct_answer_text, show_correct_answers)
@ -688,7 +688,7 @@ module QuizzesHelper
end
titles = titles.map { |title| h(title) }
title = "title=\"#{titles.join(' ')}\"".html_safe if titles.length > 0
"title=\"#{titles.join(' ')}\"".html_safe if titles.length > 0 # rubocop:disable Rails/OutputSafety
end
def show_correct_answers?

View File

@ -49,7 +49,7 @@ class Announcement < DiscussionTopic
}
def validate_draft_state_change
old_draft_state, new_draft_state = self.changes['workflow_state']
_old_draft_state, new_draft_state = self.changes['workflow_state']
self.errors.add :workflow_state, I18n.t('#announcements.error_draft_state', "This topic cannot be set to draft state because it is an announcement.") if new_draft_state == 'unpublished'
end

View File

@ -142,8 +142,7 @@ class AssessmentQuestionBank < ActiveRecord::Base
def bookmark_for(user, do_bookmark = true)
if do_bookmark
question_bank_user = self.assessment_question_bank_users.where(user_id: user).first
question_bank_user ||= self.assessment_question_bank_users.create(:user => user)
assessment_question_bank_users.where(user: user).first_or_create!
else
AssessmentQuestionBankUser.where(:user_id => user, :assessment_question_bank_id => self).delete_all
end

View File

@ -179,7 +179,7 @@ class AssetUserAccess < ActiveRecord::Base
unless @asset
return nil unless asset_code
asset_code, general = self.asset_code.split(":").reverse
asset_code, = self.asset_code.split(":").reverse
@asset = Context.find_asset_by_asset_string(asset_code, context)
@asset ||= (match = asset_code.match(/enrollment_(\d+)/)) && Enrollment.where(:id => match[1]).first
end
@ -284,9 +284,8 @@ class AssetUserAccess < ActiveRecord::Base
end
def self.infer_asset(code)
asset_code, general = code.split(":").reverse
asset = Context.find_asset_by_asset_string(asset_code)
asset
asset_code, = code.split(":").reverse
Context.find_asset_by_asset_string(asset_code)
end
# For Quizzes, we want the view score not to include the participation score

View File

@ -295,9 +295,6 @@ class AssetUserAccessLog
log_batch_size = mb_settings[:log_batch_size]
max_compaction_time = mb_settings[:max_compaction_time]
receive_timeout = mb_settings[:receive_timeout]
# semaphore to flip if we manage to advance to the "head"
# of the topic within this compaction run.
caught_up = false
early_exit = false # use to signal as soon as we've decided to bail on compaction.
positive_runtime_budget = true # set to false when budget runtime exceed allocation
@ -859,7 +856,7 @@ class AssetUserAccessLog
"(#{row["aua_id"]}, #{row["view_count"]}, '#{max_updated_at}')"
end.join(", ")
update_query = <<~SQL
<<~SQL.squish
UPDATE #{AssetUserAccess.quoted_table_name} AS aua
SET view_score = COALESCE(aua.view_score, 0) + log_segment.view_count,
updated_at = GREATEST(aua.updated_at, TO_TIMESTAMP(log_segment.max_updated_at, 'YYYY-MM-DD HH24:MI:SS.US')),

View File

@ -1016,7 +1016,7 @@ class Attachment < ActiveRecord::Base
def thumbnail_for_size(geometry)
if self.class.allows_thumbnails_of_size?(geometry)
to_use = thumbnails.loaded? ? thumbnails.detect { |t| t.thumbnail == geometry } : thumbnails.where(thumbnail: geometry).first
to_use ||= create_dynamic_thumbnail(geometry)
to_use || create_dynamic_thumbnail(geometry)
end
end
@ -1922,7 +1922,6 @@ class Attachment < ActiveRecord::Base
return filename if attempts <= 1 && block.call(filename)
new_name = filename
addition = attempts || 1
dir = File.dirname(filename)
dir = dir == "." ? "" : "#{dir}/"

View File

@ -36,7 +36,7 @@ class BookmarkService < UserService
elsif self.service == 'diigo'
Diigo::Connection.diigo_post_bookmark(self, url, title, description, tags)
end
rescue => e
rescue
# Should probably save the data to try again if it fails... at least one more try
end
end

View File

@ -998,13 +998,13 @@ class ContentMigration < ActiveRecord::Base
def imported_migration_items_for_insert_type
import_type = migration_settings[:insert_into_module_type]
imported_items = if import_type.present?
class_name = self.class.import_class_name(import_type)
imported_migration_items_hash[class_name] ||= {}
imported_migration_items_hash[class_name].values
else
imported_migration_items
end
if import_type.present?
class_name = self.class.import_class_name(import_type)
imported_migration_items_hash[class_name] ||= {}
imported_migration_items_hash[class_name].values
else
imported_migration_items
end
end
def self.import_class_name(import_type)

View File

@ -293,7 +293,7 @@ module Context
object = context.try(params[:controller].sub(/^.+\//, ''))&.find_by(id: params[:id])
end
object
rescue => e
rescue
nil
end

View File

@ -333,7 +333,7 @@ class ContextExternalTool < ActiveRecord::Base
return if self.vendor_help_link.blank?
begin
value, uri = CanvasHttp.validate_url(self.vendor_help_link)
_value, uri = CanvasHttp.validate_url(self.vendor_help_link)
self.vendor_help_link = uri.to_s
rescue URI::Error, ArgumentError
self.vendor_help_link = nil
@ -947,7 +947,7 @@ class ContextExternalTool < ActiveRecord::Base
if !context.is_a?(Account) && context.respond_to?(:context_external_tools)
tools += context.context_external_tools.having_setting(type.to_s)
end
tools += ContextExternalTool.having_setting(type.to_s).where(context_type: 'Account', context_id: context.account_chain_ids)
tools + ContextExternalTool.having_setting(type.to_s).where(context_type: 'Account', context_id: context.account_chain_ids)
end
def self.serialization_excludes; [:shared_secret, :settings]; end

View File

@ -317,7 +317,6 @@ class ContextModule < ActiveRecord::Base
end
def update_downstreams(original_position = nil)
original_position ||= self.position || 0
positions = ContextModule.module_positions(self.context).to_a.sort_by { |a| a[1] }
downstream_ids = positions.select { |a| a[1] > (self.position || 0) }.map { |a| a[0] }
downstreams = downstream_ids.empty? ? [] : self.context.context_modules.not_deleted.where(id: downstream_ids)
@ -788,7 +787,6 @@ class ContextModule < ActiveRecord::Base
end
def update_for(user, action, tag, points = nil)
retry_count = 0
return nil unless self.context.grants_right?(user, :participate_as_student)
return nil unless (progression = self.evaluate_for(user))
return nil if progression.locked?

View File

@ -43,7 +43,7 @@ module ContextModuleProgressions
GuardRail.activate(:primary) do
ContextModuleProgression.unique_constraint_retry do |retry_count|
progression = mod.context_module_progressions.where(user_id: user).first if retry_count > 0
progression ||= mod.context_module_progressions.create!(user: user)
progression || mod.context_module_progressions.create!(user: user)
end
end
end

View File

@ -434,6 +434,7 @@ class Conversation < ActiveRecord::Base
def context_name
name = context.try(:name)
name ||= Context.find_by_asset_string(context_tags.first).try(:name) if context_tags.first
name
end
def context_code

View File

@ -70,7 +70,7 @@ class ConversationBatch < ActiveRecord::Base
update_attribute :workflow_state, 'sent'
end
rescue StandardError => e
rescue
self.workflow_state = 'error'
save!
end

View File

@ -244,7 +244,6 @@ class CourseSection < ActiveRecord::Base
# This is messy, and I hate it.
# The SIS import actually gives us three names for a section
# and I don't know which one is best, or which one to show.
name_had_changed = name_changed?
# Here's the current plan:
# - otherwise, just use name
# - use the method display_name to consolidate this logic

View File

@ -206,7 +206,6 @@ class CrocodocDocument < ActiveRecord::Base
bulk_updates = {}
error_uuids = []
statuses.each do |status|
uuid, state = status['uuid'], status['status']
bulk_updates[status['status']] ||= []
bulk_updates[status['status']] << status['uuid']
if status['status'] == 'ERROR'

View File

@ -1329,7 +1329,7 @@ class Enrollment < ActiveRecord::Base
def self.cached_temporary_invitations(email)
if Enrollment.cross_shard_invitations?
Shard.birth.activate do
invitations = Rails.cache.fetch([email, 'all_invited_enrollments2'].cache_key) do
Rails.cache.fetch([email, 'all_invited_enrollments2'].cache_key) do
Shard.with_each_shard(CommunicationChannel.associated_shards(email)) do
Enrollment.invited.for_email(email).to_a
end

View File

@ -31,7 +31,7 @@ module Exporters
begin
handle = attachment.open(:need_local_file => true)
zipfile.get_output_stream(filename) { |zos| Zip::IOExtras.copy_stream(zos, handle) }
rescue => e
rescue
return false
ensure
handle.close if handle

View File

@ -50,7 +50,7 @@ class ExternalFeed < ActiveRecord::Base
def display_name(short = true)
short_url = (self.url || "").split("/")[0, 3].join("/")
res = self.title || (short ? t(:short_feed_title, "%{short_url} feed", :short_url => short_url) : self.url)
self.title || (short ? t(:short_feed_title, "%{short_url} feed", :short_url => short_url) : self.url)
end
def header_match=(str)

View File

@ -166,7 +166,6 @@ class Folder < ActiveRecord::Base
t :default_folder_name, 'New Folder'
self.name = 'New Folder' if self.name.blank?
self.name = self.name.strip.gsub(/\//, "_")
folder = self
@update_sub_folders = false
self.parent_folder_id = nil if !self.parent_folder || self.parent_folder.context != self.context || self.parent_folder_id == self.id
self.context = self.parent_folder.context if self.parent_folder

View File

@ -322,6 +322,7 @@ class Group < ActiveRecord::Base
def full_name
res = before_label(self.name) + " "
res += (self.context.course_code rescue self.context.name) if self.context
res
end
def to_atom

View File

@ -28,7 +28,6 @@ module Importers
def self.process_migration(data, migration)
assignments = data['assignments'] ? data['assignments'] : []
to_import = migration.to_import 'assignments'
create_assignments(assignments, migration)

View File

@ -28,7 +28,7 @@ module Importers
tools.each do |tool|
if migration.import_object?("context_external_tools", tool['migration_id']) || migration.import_object?("external_tools", tool['migration_id'])
begin
item = import_from_migration(tool, migration.context, migration)
import_from_migration(tool, migration.context, migration)
rescue
migration.add_import_warning(t('#migration.external_tool_type', "External Tool"), tool[:title], $!)
end

View File

@ -86,7 +86,6 @@ module Importers
end
def self.import_content(course, data, params, migration)
params ||= { :copy => {} }
logger.debug "starting import"
Importers.disable_live_events! do
@ -532,7 +531,6 @@ module Importers
Time.use_zone time_zone do
time = ActiveSupport::TimeWithZone.new(time.utc, Time.zone)
old_date = time.to_date
new_date = old_date.clone
old_start_date = options[:old_start_date]
old_end_date = options[:old_end_date]
new_start_date = options[:new_start_date]

View File

@ -192,8 +192,6 @@ module Importers
item.hide_correct_answers_at = Canvas::Migration::MigratorHelper.get_utc_time_from_timestamp(hash[:hide_correct_answers_at]) if master_migration || hash[:hide_correct_answers_at]
item.scoring_policy = hash[:which_attempt_to_keep] if master_migration || hash[:which_attempt_to_keep]
missing_links = []
unless migration.quizzes_next_migration? # The description is mapped to "instructions" in NQ
item.description = migration.convert_html(hash[:description], :quiz, hash[:migration_id], :description)
end

View File

@ -74,7 +74,6 @@ module Importers
item ||= context.wiki_pages.temp_record(:wiki => context.wiki)
item.mark_as_importing!(migration)
new_record = item.new_record?
# force the url to be the same as the url_name given, since there are
# likely other resources in the import that link to that url
if hash[:url_name].present?

View File

@ -97,7 +97,7 @@ module IncomingMail
# Can't use our usual mechanisms, so just try to send it once now
begin
Mailer.deliver(Mailer.create_message(outgoing_message))
rescue => e
rescue
# TODO: put some kind of error logging here?
end
end

View File

@ -88,7 +88,6 @@ module MasterCourses::Restrictor
def check_for_restricted_column_changes
return true if @importing_migration || !is_child_content? || !self.check_restrictions?
restrictions = nil
locked_columns = []
self.class.base_class.restricted_column_settings.each do |type, columns|
changed_columns = (self.changes.keys & columns)
@ -168,7 +167,6 @@ module MasterCourses::Restrictor
child_tag = @importing_migration.master_course_subscription.content_tag_for(self) # find or create it
return unless child_tag && child_tag.downstream_changes.present?
restrictions = nil
columns_to_restore = []
self.class.base_class.restricted_column_settings.each do |type, columns|
changed_columns = (child_tag.downstream_changes & columns) # should unlink all changes if _any_ in the category has been changed

View File

@ -53,7 +53,7 @@ class Message < ActiveRecord::Base
def deliver
message.deliver
rescue QueuedNotFound => e
rescue QueuedNotFound
raise Delayed::RetriableError, "Message does not (yet?) exist"
end
@ -663,7 +663,6 @@ class Message < ActiveRecord::Base
self.url = @message_content_link || nil
else
# Message doesn't exist so we flag the message as an error
main_link = eval(Erubi::Engine.new(self.notification.main_link || "").src)
self.subject = eval(Erubi::Engine.new(subject).src)
self.body = eval(Erubi::Engine.new(body).src)
self.transmission_errors = "couldn't find #{Canvas::MessageHelper.find_message_path(filename)}"
@ -1125,7 +1124,6 @@ class Message < ActiveRecord::Base
@exception = e
error_string = "Exception: #{e.class}: #{e.message}\n\t#{e.backtrace.join("\n\t")}"
logger.error error_string
transmission_errors = error_string
cancel
raise e
end

View File

@ -63,7 +63,7 @@ class PageView
PageView.from_attributes(pv)
end
rescue Net::ReadTimeout => e
rescue Net::ReadTimeout
raise Pv4Timeout, "failed to load page view history due to service timeout"
end

View File

@ -580,7 +580,7 @@ class Pseudonym < ActiveRecord::Base
pseudonyms = []
begin
pseudonyms = find_all_by_arbitrary_credentials(credentials, account_ids, remote_ip)
rescue ImpossibleCredentialsError => e
rescue ImpossibleCredentialsError
Rails.logger.info("Impossible pseudonym credentials: #{credentials[:unique_id]}, invalidating session")
return :impossible_credentials
end

View File

@ -71,7 +71,6 @@ module Quizzes::LogAuditing
private
def optimize(events)
answered_event_type = Quizzes::QuizSubmissionEvent::EVT_QUESTION_ANSWERED
optimizer = Quizzes::LogAuditing::QuestionAnsweredEventOptimizer.new
quiz_submission_events = events.group_by(&:quiz_submission_id)

View File

@ -54,10 +54,7 @@ module Quizzes
end
def find_by_quiz
# Find these in batches, so as to reduce the memory load
outstanding_qs = []
outstanding_qs = Quizzes::QuizSubmission.where("quiz_id = ?", @quiz.id).preload(:user).needs_grading
outstanding_qs
Quizzes::QuizSubmission.where(quiz_id: @quiz).preload(:user).needs_grading
end
end
end

View File

@ -47,8 +47,6 @@ module Quizzes::QuizQuestion::AnswerSerializers
end
pairings.each_with_index do |entry, index|
answer_id, match_id = nil, nil
unless entry.is_a?(Hash) || entry.is_a?(ActionController::Parameters)
return rc.reject :invalid_type, "answer[#{index}]", Hash
end

View File

@ -114,7 +114,7 @@ class Quizzes::QuizQuestionBuilder
# just a question
else
questions = [descriptor]
[descriptor]
end
questions.each do |question|

View File

@ -338,9 +338,8 @@ class Quizzes::QuizStatistics::StudentAnalysis < Quizzes::QuizStatistics::Report
logged_out = logged_out.where(user_id: user_ids)
end
all_submissions = []
all_submissions = prep_submissions scope
all_submissions += prep_submissions logged_out
all_submissions = prep_submissions(scope)
all_submissions + prep_submissions(logged_out)
end
end

View File

@ -1623,7 +1623,7 @@ class RoleOverride < ActiveRecord::Base
end
def self.css_class_for(context, permission, role, role_context = :role_account)
generated_permission = self.permission_for(context, permission, role, role_context = :role_account)
generated_permission = self.permission_for(context, permission, role, :role_account)
css = []
if generated_permission[:readonly]

View File

@ -406,7 +406,7 @@ class Rubric < ActiveRecord::Base
end
def update_assessments_for_new_criteria(new_criteria)
criteria = self.data
data
end
# undo innocuous changes introduced by migrations which break `will_change_with_update?`

View File

@ -288,7 +288,7 @@ class RubricAssessment < ActiveRecord::Base
def related_group_submissions_and_assessments
if active_rubric_association? && self.rubric_association.association_object.is_a?(Assignment) && !self.artifact.is_a?(ModeratedGrading::ProvisionalGrade) && !self.rubric_association.association_object.grade_group_students_individually
students = self.rubric_association.association_object.group_students(self.user).last
submissions = students.map do |student|
students.map do |student|
submission = self.rubric_association.association_object.find_asset_for_assessment(self.rubric_association, student).first
{ submission: submission,
rubric_assessments: submission.rubric_assessments

View File

@ -2287,12 +2287,7 @@ class Submission < ActiveRecord::Base
res.workflow_state = 'assigned' if res.new_record?
just_created = res.new_record?
res.send_reminder! # this method also saves the assessment_request
case obj
when User
user = obj
when Submission
obj.assign_assessment(res) if just_created
end
obj.assign_assessment(res) if obj.is_a?(Submission) && just_created
res
end
@ -2372,7 +2367,6 @@ class Submission < ActiveRecord::Base
end
def to_atom(opts = {})
prefix = self.assignment.context_prefix || ""
author_name = self.assignment.present? && self.assignment.context.present? ? self.assignment.context.name : t('atom_no_author', "No Author")
Atom::Entry.new do |entry|
entry.title = "#{self&.user.name} -- #{self&.assignment.title}#{', ' + self.assignment.context.name if opts[:include_context]}"

View File

@ -357,7 +357,7 @@ class SubmissionComment < ActiveRecord::Base
return Attachment.none unless attachment_ids.present?
ids = parse_attachment_ids
attachments = submission.assignment.attachments.where(id: ids)
submission.assignment.attachments.where(id: ids)
end
def self.preload_attachments(comments)

View File

@ -405,7 +405,7 @@ class WebConference < ActiveRecord::Base
close
end
@conference_active
rescue Errno::ECONNREFUSED => ex
rescue Errno::ECONNREFUSED
# Account credentials changed, server unreachable/down, bad stuff happened.
@conference_active = false
@conference_active

View File

@ -278,7 +278,7 @@ module Quizzes
hash = super
# legacy v1 api
unless accepts_jsonapi?
links = hash.delete('links')
hash.delete('links')
# id = hash['assignment_group']
# hash['assignment_group_id'] = quiz.assignment_group.try(:id)
else

View File

@ -450,8 +450,6 @@ class ActiveRecord::Base
num_days = options[:num_days] || 20
min_date = (options[:min_date] || max_date.advance(:days => -(num_days - 1))).midnight
offset = max_date.utc_offset
expression = "((#{column} || '-00')::TIMESTAMPTZ AT TIME ZONE '#{Time.zone.tzinfo.name}')::DATE"
result = where("#{column} >= ? AND #{column} < ?",

View File

@ -53,8 +53,8 @@ module ActiveSupport::Cache
if @value && Rails.env.test?
begin
super
rescue TypeError => e
return
rescue TypeError
nil
end
else
super

View File

@ -76,12 +76,12 @@ module YARD::Templates::Helpers::BaseHelper
raise __errmsg
end
topic, controller = *lookup_topic(appendix.namespace.to_s)
topic, _controller = *lookup_topic(appendix.namespace.to_s)
if topic
html_file = "#{topicize topic.first}.html"
bookmark = "#{appendix.name.to_s.gsub(' ', '+')}-appendix"
ret = link_url("#{html_file}##{bookmark}", appendix.title)
link_url("#{html_file}##{bookmark}", appendix.title)
else
raise __errmsg
end
@ -145,7 +145,7 @@ module YARD::Templates::Helpers::HtmlHelper
raise __errmsg
end
topic, controller = *lookup_topic(appendix.namespace.to_s)
topic, _controller = *lookup_topic(appendix.namespace.to_s)
unless topic
raise __errmsg
@ -202,7 +202,6 @@ end
def generate_swagger_json
api_resources = []
model_resources = []
options[:resources].each do |name, controllers|
view = ControllerListView.new(name, controllers)
api_resources << view.swagger_reference

View File

@ -242,7 +242,7 @@ module AdheresToPolicy
# Check the cache for the sought_right. If it exists in the cache its
# state (true or false) will be returned. Otherwise we calculate the
# state and cache it.
value, how_it_got_it = Cache.fetch(
value, _how_it_got_it = Cache.fetch(
permission_cache_key_for(user, session, sought_right),
use_rails_cache: use_rails_cache
) do
@ -252,7 +252,6 @@ module AdheresToPolicy
# Loop through all the conditions until we find the first one that
# grants us the sought_right.
conditions.any? do |condition|
condition_applies = false
start_time = Time.now
condition_applies = condition.applies?(self, user, session)
elapsed_time = Time.now - start_time

View File

@ -380,7 +380,8 @@ module AttachmentFu # :nodoc:
digest.update(line)
read_bytes = true
end
rescue => e
rescue
nil
ensure
io.close if file_from_path
end

View File

@ -298,8 +298,8 @@ module AttachmentFu # :nodoc:
# it looks like they're not always working for some reason
begin
bucket.object(old_full_filename).move_to(full_filename, :acl => attachment_options[:s3_access])
rescue => e
filename = @old_filename
rescue
nil
end
@old_filename = nil

View File

@ -22,7 +22,7 @@ class BookmarkedCollection::ConcatCollection < BookmarkedCollection::CompositeCo
def validate(bookmark)
return false unless super
bookmark, index = decompose_bookmark(bookmark)
_bookmark, index = decompose_bookmark(bookmark)
return false if index.nil?
return true

View File

@ -202,7 +202,6 @@ describe "CanvasHttp" do
end
it "checks host before running" do
res = nil
stub_request(:get, "http://www.example.com/a/b")
.to_return(body: "Hello", headers: { 'Content-Length' => 5 })
expect(CanvasHttp).to receive(:insecure_host?).with("www.example.com").and_return(true)

View File

@ -48,7 +48,7 @@ module EventStream::IndexStrategy
index_scope = index_scope.where("created_at <= ?", options[:newest]) if options[:newest].present?
index_scope = index_scope.select(:id, :created_at) if options[:just_ids] == true
event_bookmarker = EventStream::IndexStrategy::ActiveRecord::Bookmarker.new(ar_type)
bookmarked_collection = BookmarkedCollection.build(event_bookmarker) do |pager|
BookmarkedCollection.build(event_bookmarker) do |pager|
records = pager_to_records(index_scope, pager)
pager.replace(records)
pager.has_more! if records.next_page

View File

@ -62,7 +62,6 @@ describe EventStream::IndexStrategy::ActiveRecord do
describe "scope assembly" do
before :each do
query_options = {}
stream = double('stream',
:record_type => EventStream::Record,
:active_record_type => fake_record_type)

View File

@ -297,10 +297,7 @@ module HtmlTextHelper
end
processed_lines << quote_clump(quote_block) if !quote_block.empty?
message = processed_lines.join("\n")
if opts[:url]
url = add_notification_to_link(opts[:url], opts[:notification_id]) if opts[:notification_id]
links.unshift opts[:url]
end
links.unshift opts[:url] if opts[:url]
links.unshift message.html_safe
end

View File

@ -301,7 +301,6 @@ namespace :i18n do
puts "Exported en.yml, current translations unmodified (check git log for last change)"
else
`git commit -a -m"generated en.yml for translation"`
remote_branch = `git remote-ref`.strip.sub(%r{\Aremotes/[^/]+/(.*)\z}, '\\1')
local = current_branch || 'master'
`remote=$(git config branch."#{local}".remote); \
remote_ref=$(git config branch."#{local}".merge); \

View File

@ -223,7 +223,7 @@ describe IncomingMailProcessor::ImapMailbox do
exception_propegated = false
begin
@mailbox.disconnect
rescue SyntaxError => e
rescue SyntaxError
exception_propegated = true
end
expect(exception_propegated).to be_truthy

View File

@ -23,7 +23,6 @@ if Qti.migration_executable
before(:once) do
archive_file_path = File.join(BASE_FIXTURE_DIR, 'qti', 'qti_2_1.zip')
unzipped_file_path = create_temp_dir!
create_temp_dir!
exporter = Qti::Converter.new(:export_archive_path => archive_file_path, :base_download_dir => unzipped_file_path)
exporter.export
@course_data = exporter.course.with_indifferent_access

View File

@ -32,7 +32,7 @@ describe "RequestContext::Session" do
end
Rails.application = app_class.new
env = { 'rack.session.options' => { id: 'abc' } }
_, headers, _ = RequestContext::Session.new(->(env) {
RequestContext::Session.new(->(_env) {
[200, {}, []]
}).call(env)
expect(env['action_dispatch.cookies']['log_session_id']).to eq 'abc'

View File

@ -153,7 +153,7 @@ module Api
element[att] = val
end
end
rescue URI::Error => e
rescue URI::Error
# leave it as is
end
end

View File

@ -22,6 +22,6 @@ module Api::V1::PostGradesStatus
include Api::V1::Json
def post_grades_status_json(course_or_section)
res = course_or_section.sis_post_grades_statuses.last.as_json(:only => %w(id course_id course_section_id status message grades_posted_at))
course_or_section.sis_post_grades_statuses.last.as_json(:only => %w(id course_id course_section_id status message grades_posted_at))
end
end

View File

@ -101,7 +101,6 @@ class BrandConfigRegenerator
new_config = config.clone_with_new_parent(new_parent_md5)
new_config.save_unless_dup!
account = thing.is_a?(SharedBrandConfig) ? thing.account : thing
job_type = thing.is_a?(SharedBrandConfig) ? :sync_to_s3_and_save_to_shared_brand_config! : :sync_to_s3_and_save_to_account!
new_config.send(job_type, @progress, thing)

View File

@ -230,7 +230,7 @@ module Canvas
begin
Timeout.timeout(timeout, &block)
rescue Timeout::Error => e
rescue Timeout::Error
error_ttl = timeout_protection_error_ttl(service_name)
redis.incrby(redis_key, 1)
redis.expire(redis_key, error_ttl)

View File

@ -42,7 +42,7 @@ module Canvas
dynamodb = canvas_ddb.client
local_table_name = canvas_ddb.prefixed_table_name(table_name)
exists = begin
result = dynamodb.describe_table(table_name: local_table_name)
dynamodb.describe_table(table_name: local_table_name)
true
rescue Aws::DynamoDB::Errors::ResourceNotFoundException
false

View File

@ -62,7 +62,6 @@ class Canvas::Migration::Worker::ZipFileWorker < Canvas::Migration::Worker::Base
)
zipfile.close
zipfile = nil
cm.workflow_state = :imported
cm.save

View File

@ -108,7 +108,7 @@ module Canvas::Plugins::TicketingSystem
become_user_uri.query = (Hash[*(become_user_uri.query || '')
.split('&').map { |part| part.split('=') }.flatten])
.merge({ 'become_user_id' => user_id }).to_query
rescue URI::Error => e
rescue URI::Error
become_user_uri = "unable to parse uri: #{url}"
end
become_user_uri.to_s

View File

@ -283,7 +283,7 @@ module CC
@rewriter.set_handler('items') do |match|
item = ContentTag.find(match.obj_id)
migration_id = @key_generator.create_key(item)
new_url = "#{COURSE_TOKEN}/modules/#{match.type}/#{migration_id}#{match.query}"
"#{COURSE_TOKEN}/modules/#{match.type}/#{migration_id}#{match.query}"
end
@rewriter.set_default_handler do |match|
new_url = match.url
@ -347,24 +347,24 @@ module CC
media_id = anchor['id'].gsub(/^media_comment_/, '')
obj = MediaObject.active.by_media_id(media_id).first
if obj && (migration_id = @key_generator.create_key(obj))
@used_media_objects << obj
info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor)
@media_object_infos[obj.id] = info
anchor['href'] = File.join(WEB_CONTENT_TOKEN, info[:path])
end
next unless obj && @key_generator.create_key(obj)
@used_media_objects << obj
info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor)
@media_object_infos[obj.id] = info
anchor['href'] = File.join(WEB_CONTENT_TOKEN, info[:path])
end
# process new RCE media iframes too
doc.css('iframe[data-media-id]').each do |iframe|
media_id = iframe['data-media-id']
obj = MediaObject.active.by_media_id(media_id).take
if obj && (migration_id = @key_generator.create_key(obj))
@used_media_objects << obj
info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor)
@media_object_infos[obj.id] = info
iframe['src'] = File.join(WEB_CONTENT_TOKEN, info[:path])
end
next unless obj && @key_generator.create_key(obj)
@used_media_objects << obj
info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor)
@media_object_infos[obj.id] = info
iframe['src'] = File.join(WEB_CONTENT_TOKEN, info[:path])
end
# prepend the Canvas domain to remaining absolute paths that are missing the host
@ -380,7 +380,7 @@ module CC
if !url.host && url_str[0] == '/'[0]
element[attribute] = "#{@url_prefix}#{url_str}"
end
rescue URI::Error => e
rescue URI::Error
# leave it as is
end
end
@ -432,7 +432,7 @@ module CC
Rack::Utils.parse_query(uri.query).each do |k, v|
qs << "canvas_qs_#{Rack::Utils.escape(k)}=#{Rack::Utils.escape(v)}"
end
rescue URI::Error => e
rescue URI::Error
# if we can't parse the url, we can't preserve canvas query params
end
return nil if qs.blank?

View File

@ -33,7 +33,7 @@ module CC::Exporter::Epub::Converters
return flv_path unless mp4_url.present?
# Maybe a weird exception to catch, but that's what ends up being thrown
# if we pass a media_id that doesn't have a corresponding set of assets.
rescue NoMethodError => e
rescue NoMethodError
return flv_path
end

View File

@ -42,8 +42,7 @@ module CC::Importer::Canvas
end
# exports the package into the intermediary json
def export(to_export = SCRAPE_ALL_HASH)
to_export = SCRAPE_ALL_HASH.merge to_export if to_export
def export(_to_export = SCRAPE_ALL_HASH)
unzip_archive
set_progress(5)

View File

@ -83,7 +83,7 @@ module CC::Importer::Standard
def parse_canvas_assignment_data(meta_doc, html_doc = nil, assignment = {})
if html_doc
title, body = get_html_title_and_body(html_doc)
_title, body = get_html_title_and_body(html_doc)
assignment['description'] = body
end

View File

@ -58,7 +58,6 @@ module CopyAuthorizedLinks
end
def copy_authorized_links_to_context
block = self.class.copy_authorized_links_block rescue nil
columns = (self.class.copy_authorized_links_columns || []).compact
columns.each do |column|
if column == :custom
@ -68,8 +67,6 @@ module CopyAuthorizedLinks
else
html = self.read_attribute(column) rescue nil
if html && !html.empty?
context, inferred_user = self.instance_eval(&block) if block
user = @copy_authorized_links_override_user || inferred_user
self.write_attribute(column, html) if html && !html.empty?
end
end

View File

@ -278,7 +278,7 @@ class CourseLinkValidator
return :unpublished_item if object.workflow_state == 'unpublished'
end
nil
rescue => e
rescue
:missing_item
end

View File

@ -23,7 +23,7 @@ module CustomValidations
def validates_as_url(*fields, allowed_schemes: %w{http https})
validates_each(fields, :allow_nil => true) do |record, attr, value|
begin
value, uri = CanvasHttp.validate_url(value, allowed_schemes: allowed_schemes)
value, = CanvasHttp.validate_url(value, allowed_schemes: allowed_schemes)
record.send("#{attr}=", value)
rescue CanvasHttp::Error, URI::Error, ArgumentError

View File

@ -25,14 +25,14 @@ module DataFixup::CreateLtiLinksForLegacyLtiToolSettings
.where.not(resource_link_id: nil).find_each do |tool_setting|
Lti::Link.transaction do
originality_report = OriginalityReport.find_by(link_id: tool_setting.resource_link_id)
link = Lti::Link.create_with({
product_code: tool_setting.product_code,
vendor_code: tool_setting.vendor_code,
resource_type_code: tool_setting.resource_type_code,
custom_parameters: tool_setting.custom_parameters,
resource_url: tool_setting.resource_url,
linkable: originality_report
}).find_or_create_by!(resource_link_id: tool_setting.resource_link_id)
Lti::Link.create_with({
product_code: tool_setting.product_code,
vendor_code: tool_setting.vendor_code,
resource_type_code: tool_setting.resource_type_code,
custom_parameters: tool_setting.custom_parameters,
resource_url: tool_setting.resource_url,
linkable: originality_report
}).find_or_create_by!(resource_link_id: tool_setting.resource_link_id)
end
end
end

View File

@ -27,7 +27,6 @@ module DataFixup::ReinsertAssessmentQuestionFileVerifiers
if links.any?
att_id_map = Hash[links.map { |l| [l, l.match(/\/assessment_questions\/\d+\/files\/(\d+)/)[1].to_i] }]
uuid_map = Hash[Attachment.where(:id => att_id_map.values, :context_type => "AssessmentQuestion").pluck(:id, :uuid)]
new_data = data
links.each do |link|
uuid = uuid_map[att_id_map[link]]
next unless uuid # just in case somehow the attachment disappeared

View File

@ -870,7 +870,7 @@ class GradeCalculator
max_total = (submissions + cant_drop).map { |s| s[:total] }.max
kept = keep_highest(submissions, cant_drop, n_highest, max_total)
kept = keep_lowest(kept, cant_drop, n_lowest, max_total)
keep_lowest(kept, cant_drop, n_lowest, max_total)
end
def keep_highest(submissions, cant_drop, keep, max_total)

View File

@ -642,7 +642,8 @@ class GradebookImporter
# If the number of fields generated by this separator is consistent for all lines,
# we should be able to assume it's a valid delimiter for this file
field_counts[separator] = field_count_by_row.first if field_count_by_row.uniq.size == 1
rescue CSV::MalformedCSVError => e
rescue CSV::MalformedCSVError
nil
end
end

View File

@ -334,7 +334,7 @@ module InstFS
# floor_to rounds `number` down to a multiple of the chosen step.
def floor_to(number, step)
whole, remainder = number.divmod(step)
whole, = number.divmod(step)
whole * step
end

View File

@ -80,12 +80,10 @@ class MessageDispatcher < Delayed::PerformableMethod
raise ActiveRecord::RecordNotFound unless messages.length == queued.length
end
messages.each do |message|
begin
message.deliver
rescue Exception, Timeout::Error => e
# this delivery failed, we'll have to make an individual job to retry
self.dispatch(message)
end
message.deliver
rescue
# this delivery failed, we'll have to make an individual job to retry
self.dispatch(message)
end
end
end

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