RuboCop: Lint/UnusedBlockArgument config,doc,gems,lib

all manual

Change-Id: I8bb9c11634b0e2b2c8a79dd6f8f2cb71eaa90450
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/276628
Tested-by: Service Cloud Jenkins <svc.cloudjenkins@instructure.com>
Reviewed-by: Jacob Burroughs <jburroughs@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-22 13:50:42 -06:00
parent 38427e3e3e
commit a0a399136a
53 changed files with 126 additions and 126 deletions

View File

@ -280,7 +280,7 @@ module CanvasRails
# don't wrap fields with errors with a <div class="fieldWithErrors" />,
# since that could leak information (e.g. valid vs invalid username on
# login page)
config.action_view.field_error_proc = Proc.new { |html_tag, instance| html_tag }
config.action_view.field_error_proc = proc { |html_tag, _instance| html_tag }
class ExceptionsApp
def call(env)

View File

@ -691,7 +691,7 @@ class ActiveRecord::Base
def self.bulk_insert(records)
return if records.empty?
array_columns = records.first.select { |k, v| v.is_a?(Array) }.map(&:first)
array_columns = records.first.select { |_k, v| v.is_a?(Array) }.keys
array_columns.each do |column_name|
cast_type = connection.send(:lookup_cast_type_from_column, self.columns_hash[column_name.to_s])
records.each do |row|

View File

@ -99,7 +99,7 @@ Rails.application.config.after_initialize do
end
end
Delayed::Worker.on_max_failures = proc do |job, err|
Delayed::Worker.on_max_failures = proc do |_job, err|
# We don't want to keep around max_attempts failed jobs that failed because the
# underlying AR object was destroyed.
# All other failures are kept for inspection.

View File

@ -22,7 +22,7 @@ class StubbedClient
events = records.map { |e| JSON.parse(e[:data]).dig('attributes', 'event_name') }.join(' | ')
puts "Events #{events} put to stream #{stream_name}: #{records}"
OpenStruct.new(
records: records.map { |r| OpenStruct.new(error_code: 'failure', error_message: 'this fails') }
records: records.map { OpenStruct.new(error_code: 'failure', error_message: 'this fails') }
)
end

View File

@ -97,12 +97,12 @@ module YARD::Templates::Helpers::BaseHelper
def lookup_topic(controller_path)
controller = nil
topic = options[:resources].find { |r, cs|
topic = options[:resources].find do |_r, cs|
cs.any? { |c|
controller = c if c.path.to_s == controller_path
!controller.nil?
}
}
end
[topic, controller]
end

View File

@ -20,7 +20,7 @@
def init
if options[:all_resources]
options[:controllers] = options[:resources].map { |r, c| c }.flatten
options[:controllers] = options[:resources].flat_map(&:last)
sections :header, :method_details_list, [T('method_details')]
else
sections :header, [:topic_doc, :method_details_list, [T('method_details')]]

View File

@ -53,32 +53,18 @@ module ActiveRecord
configuration = { :column => "position" }
configuration.update(options) if options.is_a?(Hash)
if !configuration[:scope]
scope_condition_method = <<-RUBY
def scope_condition
nil
end
def in_scope?
true
end
def list_scope_base
self.class.base_class.all
end
RUBY
else
if configuration[:scope]
scope = configuration[:scope]
# translate symbols and arrays to hash format
scope = case scope
when Symbol
{ scope => self }
when Array
Hash[scope.map { |symbol| [symbol, self] }]
scope.index_with { self }
when Hash
scope
else
raise ArgumentError.new("scope must be nil, a symbol, an array, or a hash")
raise ArgumentError, "scope must be nil, a symbol, an array, or a hash"
end
# expand assocations to their foreign keys
new_scope = {}
@ -97,13 +83,13 @@ module ActiveRecord
scope = new_scope
# build the conditions hash, using literal values or the attribute if it's self
conditions = Hash[scope.map { |k, v| [k, v == self ? k : v.inspect] }]
conditions = scope.map { |k, v| [k, v == self ? k : v.inspect] }.to_h
conditions = conditions.map { |c, v| "#{c}: #{v}" }.join(', ')
# build the in_scope method, matching literals or requiring a foreign keys
# to be non-nil
in_scope_conditions = []
variable_conditions, constant_conditions = scope.partition { |k, v| v == self }
in_scope_conditions.concat(variable_conditions.map { |c, v| "!#{c}.nil?" })
variable_conditions, constant_conditions = scope.partition { |_k, v| v == self }
in_scope_conditions.concat(variable_conditions.map { |c, _v| "!#{c}.nil?" })
in_scope_conditions.concat(constant_conditions.map do |c, v|
if v.is_a?(Array)
"#{v.inspect}.include?(#{c})"
@ -112,7 +98,7 @@ module ActiveRecord
end
end)
scope_condition_method = <<-RUBY
scope_condition_method = <<~RUBY
def scope_condition
{ #{conditions} }
end
@ -125,6 +111,20 @@ module ActiveRecord
self.class.base_class.where(scope_condition)
end
RUBY
else
scope_condition_method = <<~RUBY
def scope_condition
nil
end
def in_scope?
true
end
def list_scope_base
self.class.base_class.all
end
RUBY
end
class_eval <<-RUBY, __FILE__, __LINE__ + 1

View File

@ -22,11 +22,13 @@ class BookmarkedCollection::CompositeProxy < BookmarkedCollection::Proxy
attr_reader :collections
def initialize(collections)
super(nil, nil)
@labels = collections.map(&:first)
@depth = collections.map { |(_, coll)| coll.depth }.max + 1
@collections = collections.map do |(label, coll)|
adjustment = @depth - 1 - coll.depth
adjustment.times.inject(coll) { |c, i| BookmarkedCollection.concat([label, c]) }
adjustment.times.inject(coll) { |c, _i| BookmarkedCollection.concat([label, c]) }
end
end

View File

@ -109,7 +109,7 @@ describe BookmarkedCollection::Proxy do
it "doesn't blow up when filtering everything out" do
bookmarker = BookmarkedCollection::SimpleBookmarker.new(@scope.klass, :id)
@proxy = BookmarkedCollection.wrap(bookmarker, @scope)
@proxy = BookmarkedCollection.filter(@proxy) do |item|
@proxy = BookmarkedCollection.filter(@proxy) do
false
end
collection = @proxy.instance_variable_get(:@collection)

View File

@ -23,7 +23,7 @@ module BroadcastPolicy
def initialize(dispatch)
self.dispatch = dispatch
self.recipient_filter = lambda { |record, user| record }
self.recipient_filter = lambda { |record, _user| record }
end
# This should be called for an instance. It can only be sent out if the

View File

@ -22,8 +22,8 @@ require_relative '../spec_helper'
describe BroadcastPolicy::NotificationPolicy do
let(:subject) do
policy = BroadcastPolicy::NotificationPolicy.new(:test_notification)
policy.to = ->(record) { ['user@example.com', 'user2@example.com'] }
policy.whenever = ->(record) { true }
policy.to = proc { ['user@example.com', 'user2@example.com'] }
policy.whenever = proc { true }
policy
end

View File

@ -175,7 +175,7 @@ module CanvasCassandra
# updating columns with nil values, rather than creating tombstone delete
# records for them
def insert_record(table_name, primary_key_attrs, changes, ttl_seconds = nil, execute_options: {})
changes = changes.reject { |k, v| v.is_a?(Array) ? v.last.nil? : v.nil? }
changes = changes.reject { |_k, v| v.is_a?(Array) ? v.last.nil? : v.nil? }
update_record(table_name, primary_key_attrs, changes, ttl_seconds, execute_options: execute_options)
end
@ -204,7 +204,10 @@ module CanvasCassandra
# => ["name = ? AND state = ?", ["foo", "ut"]]
def build_where_conditions(conditions)
where_args = []
where_clause = conditions.sort_by { |k, v| k.to_s }.map { |k, v| where_args << v; "#{k} = ?" }.join(" AND ")
where_clause = conditions.sort.map do |k, v|
where_args << v
"#{k} = ?"
end.join(" AND ")
return where_clause, where_args
end
@ -219,18 +222,12 @@ module CanvasCassandra
protected
def stringify_hash(hash)
hash.dup.tap do |new_hash|
new_hash.keys.each { |k| new_hash[k.to_s] = new_hash.delete(k) unless k.is_a?(String) }
end
end
def do_update_record(table_name, primary_key_attrs, changes, ttl_seconds, execute_options: {})
primary_key_attrs = stringify_hash(primary_key_attrs)
changes = stringify_hash(changes)
primary_key_attrs = primary_key_attrs.stringify_keys
changes = changes.stringify_keys
where_clause, where_args = build_where_conditions(primary_key_attrs)
primary_key_attrs.each do |key, value|
primary_key_attrs.each_key do |key|
if changes[key].is_a?(Array) && !changes[key].first.nil?
raise ArgumentError, "Cannot change the primary key of a record, attempted to change #{key} #{changes[key].inspect}"
end
@ -238,13 +235,13 @@ module CanvasCassandra
deletes, updates = changes.
# normalize the values since we accept two formats
map { |key, val| [key, val.is_a?(Array) ? val.last : val] }.
transform_values { |val| val.is_a?(Array) ? val.last : val }.
# reject values that are part of the primary key, since those are in the where clause
reject { |key, val| primary_key_attrs.key?(key) }.
except(*primary_key_attrs.keys).
# sort, just so the generated cql is deterministic
sort_by(&:first).
# split changes into updates and deletes
partition { |key, val| val.nil? }
partition { |_key, val| val.nil? }
# inserts and updates in cassandra are equivalent,
# so no need to differentiate here

View File

@ -116,7 +116,7 @@ describe CanvasHttp::CircuitBreaker do
end
it "uses default values if the configuration block is broken" do
CanvasHttp::CircuitBreaker.threshold = ->(domain) { nil }
CanvasHttp::CircuitBreaker.threshold = proc {}
expect(CanvasHttp::CircuitBreaker.threshold("some.domain.com")).to eq(CanvasHttp::CircuitBreaker::DEFAULT_THRESHOLD)
end
end

View File

@ -54,7 +54,7 @@ describe CanvasKaltura::ClientV3 do
before(:each) do
CanvasKaltura.cache = double(read: nil)
CanvasKaltura.logger = double.as_null_object
CanvasKaltura.timeout_protector_proc = lambda { |options, &block| block.call }
CanvasKaltura.timeout_protector_proc = lambda { |_options, &block| block.call }
create_config
WebMock.enable!
end

View File

@ -27,7 +27,7 @@ describe CanvasKaltura do
end
it "call timeout protector if set" do
CanvasKaltura.timeout_protector_proc = lambda { |options, &block| 27 }
CanvasKaltura.timeout_protector_proc = proc { 27 }
expect(CanvasKaltura.with_timeout_protector).to be 27
end
end

View File

@ -46,7 +46,7 @@ module CanvasPartman
.pluck(:id, base_class.partitioning_field)
break if id_dates.empty?
id_dates.group_by { |id, date| generate_name_for_partition(date) }.each do |partition_table, part_id_dates|
id_dates.group_by { |_id, date| generate_name_for_partition(date) }.each do |partition_table, part_id_dates|
base_class.connection.execute(<<-SQL)
WITH x AS (
DELETE FROM ONLY #{base_class.quoted_table_name}

View File

@ -46,6 +46,6 @@ module CanvasPartmanTest::SchemaHelper
end
end
RSpec.configure do |config|
RSpec.configure do
SchemaHelper = CanvasPartmanTest::SchemaHelper
end

View File

@ -5,6 +5,6 @@
guard :rspec do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec" }
watch(%r{^lib/(.+)\.rb$}) { "spec" }
watch('spec/spec_helper.rb') { "spec" }
end

View File

@ -61,21 +61,21 @@ module CanvasQuizStatistics::Analyzers
# Number of students who filled all blanks correctly.
#
# @return [Integer]
metric :correct => [:grades] do |responses, grades|
metric :correct => [:grades] do |_responses, grades|
grades.select { |r| r == 'true' }.length
end
# Number of students who filled one or more blanks correctly.
#
# @return [Integer]
metric :partially_correct => [:grades] do |responses, grades|
metric :partially_correct => [:grades] do |_responses, grades|
grades.select { |r| r == 'partial' }.length
end
# Number of students who didn't fill any blank correctly.
#
# @return [Integer]
metric :incorrect => [:grades] do |responses, grades|
metric :incorrect => [:grades] do |_responses, grades|
grades.select { |r| Base::Constants::FalseLike.include?(r) }.length
end

View File

@ -111,7 +111,7 @@ module CanvasQuizStatistics::Analyzers
# }
# ]
# }
metric :answer_sets => [:answers, :matches] do |responses, answers, matches|
metric :answer_sets => [:answers, :matches] do |responses, _answers, matches|
answer_sets = parse_answers do |answer, stats|
stats[:answers] = matches.map do |match|
build_answer(match[:match_id],

View File

@ -70,7 +70,7 @@ describe CanvasQuizStatistics::Analyzers::Base do
{ colors: responses.map { |r| r[:color] } }
end
metric something: [:colors] do |responses, colors|
metric something: [:colors] do |_responses, colors|
colors.join(', ')
end
end

View File

@ -152,7 +152,7 @@ class CanvasUnzip
def self.compute_uncompressed_size(archive_filename)
total_size = 0
each_entry(archive_filename) { |entry, index| total_size += entry.size }
each_entry(archive_filename) { |entry, _index| total_size += entry.size }
total_size
end

View File

@ -21,8 +21,8 @@
module EventStream::AttrConfig
module ClassMethods
CASTS = {
String => lambda { |name, value| value.to_s },
Integer => lambda { |name, value| value.to_i },
String => lambda { |_name, value| value.to_s },
Integer => lambda { |_name, value| value.to_i },
Proc => lambda { |name, value|
return value if value.nil? || value.respond_to?(:call)

View File

@ -73,7 +73,7 @@ describe EventStream::Backend::ActiveRecord do
table :items_by_optional_index
entry_proc lambda { |record| [record.field, record.id] if record.id > 0 }
key_proc lambda { |i1, i2| [i1, i2] }
ar_scope_proc lambda { |v1, v2| ar_cls.where({ key: :val }) }
ar_scope_proc lambda { |_v1, _v2| ar_cls.where({ key: :val }) }
end
end
s.raise_on_error = true

View File

@ -68,7 +68,7 @@ describe EventStream::IndexStrategy::ActiveRecord do
ar_cls = fake_record_type
base_index = EventStream::Index.new(stream) do
self.table "table"
self.entry_proc lambda { |a1, a2| nil }
self.entry_proc lambda { |_a1, _a2| }
self.ar_scope_proc lambda { |a1, a2| ar_cls.where({ one: a1.id, two: a2.id }) }
end
@index = base_index.strategy_for(:active_record)

View File

@ -278,7 +278,7 @@ module HtmlTextHelper
message = HtmlTextHelper.escape_html(message)
# now put the links back in
message = message.gsub(AUTO_LINKIFY_PLACEHOLDER) do |match|
message = message.gsub(AUTO_LINKIFY_PLACEHOLDER) do
placeholder_blocks.shift
end

View File

@ -67,7 +67,7 @@ module I18nTasks
when :abort then
throw(:abort)
when :discard then
@new_translations.delete_if do |k, v|
@new_translations.delete_if do |k, _v|
mismatches.any? { |m| m.key == k }
end
when :accept then

View File

@ -318,7 +318,7 @@ namespace :i18n do
end
desc "Validates and imports new translations"
task :import, [:source_file, :translated_file] => :environment do |t, args|
task :import, [:source_file, :translated_file] => :environment do |_t, args|
require 'open-uri'
Hash.include I18nTasks::HashExtensions unless Hash.new.kind_of?(I18nTasks::HashExtensions)
@ -368,7 +368,7 @@ namespace :i18n do
end
desc "Imports new translations, ignores missing or unexpected keys"
task :autoimport, [:translated_file, :source_file] => :environment do |t, args|
task :autoimport, [:translated_file, :source_file] => :environment do |_t, args|
require 'open-uri'
if args[:source_file].present?
@ -388,7 +388,7 @@ namespace :i18n do
process = ->(node) do
case node
when Hash
node.delete_if { |k, v| process.call(v).nil? }
node.delete_if { |_k, v| process.call(v).nil? }
when Proc
nil
else
@ -498,18 +498,18 @@ namespace :i18n do
end
desc "Download language files from Transifex"
task :transifex, [:user, :password, :languages] do |t, args|
task :transifex, [:user, :password, :languages] do |_t, args| # rubocop:disable Rails/RakeEnvironment
languages = transifex_languages(args[:languages])
transifex_download(args[:user], args[:password], languages)
end
desc "Download language files from Transifex and import them"
task :transifeximport, [:user, :password, :languages, :source_file] => :environment do |t, args|
task :transifeximport, [:user, :password, :languages, :source_file] => :environment do |_t, args|
import_languages(:transifex, args)
end
desc "Download language files from s3 and import them"
task :s3import, [:s3_bucket, :languages, :source_file] => :environment do |t, args|
task :s3import, [:s3_bucket, :languages, :source_file] => :environment do |_t, args|
import_languages(:s3, args)
end

View File

@ -108,7 +108,7 @@ describe IncomingMailProcessor::DirectoryMailbox do
it "deletes files" do
expect(@mailbox).to receive(:delete_file).with(default_config[:folder], "foo")
@mailbox.each_message do |id, body|
@mailbox.each_message do |id, _body|
@mailbox.delete_message(id)
end
end
@ -118,7 +118,7 @@ describe IncomingMailProcessor::DirectoryMailbox do
expect(@mailbox).to receive(:move_file).with(folder, "foo", "aside")
expect(@mailbox).to receive(:folder_exists?).with(folder, "aside").and_return(true)
expect(@mailbox).to receive(:create_folder).never
@mailbox.each_message do |id, body|
@mailbox.each_message do |id, _body|
@mailbox.move_message(id, "aside")
end
end
@ -128,7 +128,7 @@ describe IncomingMailProcessor::DirectoryMailbox do
expect(@mailbox).to receive(:move_file).with(folder, "foo", "aside")
expect(@mailbox).to receive(:folder_exists?).with(folder, "aside").and_return(false)
expect(@mailbox).to receive(:create_folder).with(default_config[:folder], "aside")
@mailbox.each_message do |id, body|
@mailbox.each_message do |id, _body|
@mailbox.move_message(id, "aside")
end
end

View File

@ -155,7 +155,7 @@ describe IncomingMailProcessor::ImapMailbox do
expect(@imap_mock).to receive(:search).and_return([42])
expect(@imap_mock).to receive(:fetch).and_return(mock_fetch_response("body"))
expect(@imap_mock).to receive(:store).with(42, "+FLAGS", Net::IMAP::DELETED)
@mailbox.each_message do |id, body|
@mailbox.each_message do |id, _body|
@mailbox.delete_message(id)
end
end
@ -166,7 +166,7 @@ describe IncomingMailProcessor::ImapMailbox do
expect(@imap_mock).to receive(:list).and_return([double.as_null_object])
expect(@imap_mock).to receive(:copy).with(42, "other_folder")
expect(@imap_mock).to receive(:store).with(42, "+FLAGS", Net::IMAP::DELETED)
@mailbox.each_message do |id, body|
@mailbox.each_message do |id, _body|
@mailbox.move_message(id, "other_folder")
end
end
@ -178,7 +178,7 @@ describe IncomingMailProcessor::ImapMailbox do
expect(@imap_mock).to receive(:create).with("other_folder")
expect(@imap_mock).to receive(:copy).with(42, "other_folder")
expect(@imap_mock).to receive(:store).with(42, "+FLAGS", Net::IMAP::DELETED)
@mailbox.each_message do |id, body|
@mailbox.each_message do |id, _body|
@mailbox.move_message(id, "other_folder")
end
end
@ -190,7 +190,7 @@ describe IncomingMailProcessor::ImapMailbox do
expect(@imap_mock).to receive(:create).with("other_folder")
expect(@imap_mock).to receive(:copy).with(42, "other_folder")
expect(@imap_mock).to receive(:store).with(42, "+FLAGS", Net::IMAP::DELETED)
@mailbox.each_message do |id, body|
@mailbox.each_message do |id, _body|
@mailbox.move_message(id, "other_folder")
end
end

View File

@ -595,7 +595,7 @@ describe IncomingMailProcessor::IncomingMessageProcessor do
})
processed_second = false
TimeoutMailbox.send(:define_method, :each_message) do |opts|
TimeoutMailbox.send(:define_method, :each_message) do |**|
if @config[:username] == 'first'
raise Timeout::Error
else

View File

@ -155,14 +155,14 @@ describe IncomingMailProcessor::Pop3Mailbox do
it "deletes when asked" do
expect(@foo).to receive(:delete)
@mailbox.each_message do |message_id, body|
@mailbox.each_message do |message_id, _body|
@mailbox.delete_message(message_id)
end
end
it "deletes when asked to move" do
expect(@foo).to receive(:delete)
@mailbox.each_message do |message_id, body|
@mailbox.each_message do |message_id, _body|
@mailbox.move_message(message_id, "anything")
end
end

View File

@ -33,7 +33,7 @@ describe PaginatedCollection do
describe '#paginate' do
it 'uses the provided collection' do
expect { PaginatedCollection.build { |pager| [] }.paginate(:per_page => 5) }.to raise_error(ArgumentError)
expect { PaginatedCollection.build { [] }.paginate(:per_page => 5) }.to raise_error(ArgumentError)
items = PaginatedCollection.build { |pager| pager.replace([1, 2]) }.paginate(:page => 1, :per_page => 5)
expect(items).to eq [1, 2]
expect(items.size).to eq 2

View File

@ -27,7 +27,7 @@ describe "RequestContext::Generator" do
let(:context) { double('Course', class: 'Course', id: 15) }
it "generates the X-Canvas-Meta response header" do
_, headers, _ = RequestContext::Generator.new(->(env) {
_, headers, = RequestContext::Generator.new(->(_env) {
RequestContext::Generator.add_meta_header("a1", "test1")
RequestContext::Generator.add_meta_header("a2", "test2")
RequestContext::Generator.add_meta_header("a3", "")
@ -37,7 +37,7 @@ describe "RequestContext::Generator" do
end
it "adds request data to X-Canvas-Meta" do
_, headers, _ = RequestContext::Generator.new(->(env) {
_, headers, = RequestContext::Generator.new(->(_env) {
RequestContext::Generator.add_meta_header("a1", "test1")
RequestContext::Generator.store_request_meta(request, nil)
[200, {}, []]
@ -46,7 +46,7 @@ describe "RequestContext::Generator" do
end
it "adds request and context data to X-Canvas-Meta" do
_, headers, _ = RequestContext::Generator.new(->(env) {
_, headers, = RequestContext::Generator.new(->(_env) {
RequestContext::Generator.add_meta_header("a1", "test1")
RequestContext::Generator.store_request_meta(request, context)
[200, {}, []]
@ -88,13 +88,13 @@ describe "RequestContext::Generator" do
it "generates a request_id and store it in Thread.current" do
Thread.current[:context] = nil
_, _, _ = RequestContext::Generator.new(->(env) { [200, {}, []] }).call(env)
RequestContext::Generator.new(->(_env) { [200, {}, []] }).call(env)
expect(Thread.current[:context][:request_id]).to be_present
end
it "adds the request_id to X-Request-Context-Id" do
Thread.current[:context] = nil
_, headers, _ = RequestContext::Generator.new(->(env) {
_, headers, = RequestContext::Generator.new(->(_env) {
[200, {}, []]
}).call(env)
expect(headers['X-Request-Context-Id']).to be_present
@ -103,14 +103,14 @@ describe "RequestContext::Generator" do
it "finds the session_id in a cookie and store it in Thread.current" do
Thread.current[:context] = nil
env['action_dispatch.cookies'] = { log_session_id: 'abc' }
_, _, _ = RequestContext::Generator.new(->(env) { [200, {}, []] }).call(env)
RequestContext::Generator.new(->(_env) { [200, {}, []] }).call(env)
expect(Thread.current[:context][:session_id]).to eq 'abc'
end
it "finds the session_id from the rack session and add it to X-Session-Id" do
Thread.current[:context] = nil
env['rack.session.options'] = { id: 'abc' }
_, headers, _ = RequestContext::Generator.new(->(env) {
_, headers, = RequestContext::Generator.new(->(_env) {
[200, {}, []]
}).call(env)
expect(headers['X-Session-Id']).to eq 'abc'
@ -120,7 +120,7 @@ describe "RequestContext::Generator" do
Timecop.freeze do
Thread.current[:context] = nil
env['HTTP_X_REQUEST_START'] = "t=#{(1.minute.ago.to_f * 1000000).to_i}"
_, headers, _ = RequestContext::Generator.new(->(env) {
_, headers, = RequestContext::Generator.new(->(_env) {
[200, {}, []]
}).call(env)
q = headers["X-Canvas-Meta"].match(/q=(\d+)/)[1].to_f

View File

@ -27,7 +27,7 @@ module Api::V1
day_hash = Hash.new { |hash, date| hash[date] = { :graders => {} } }
submissions_set(course, api_context)
.each_with_object(day_hash) { |submission, day| update_graders_hash(day[day_string_for(submission)][:graders], submission, api_context) }
.each do |date, date_hash|
.each_value do |date_hash|
compress(date_hash, :graders)
date_hash[:graders].each { |grader| compress(grader, :assignments) }
end
@ -37,8 +37,9 @@ module Api::V1
def json_for_date(date, course, api_context)
submissions_set(course, api_context, :date => date)
.each_with_object({}) { |sub, memo| update_graders_hash(memo, sub, api_context) }.values
.each { |grader| compress(grader, :assignments) }
.each_with_object({}) { |sub, memo| update_graders_hash(memo, sub, api_context) }
.each_value { |grader| compress(grader, :assignments) }
.values
end
def version_json(course, version, api_context, opts = {})

View File

@ -187,7 +187,7 @@ module Api::V1::OutcomeResults
# is in multiple sections, they will have multiple rollup results. pagination is
# still by user, so the counts won't match up. again, this is a very rare thing
section_ids_func = if @section
->(user) { [@section.id] }
->(_user) { [@section.id] }
else
enrollments = @context.all_accepted_student_enrollments.where(:user_id => serialized_rollup_pairs.map { |pair| pair[0].context.id }).to_a
->(user) { enrollments.select { |e| e.user_id == user.id }.map(&:course_section_id) }

View File

@ -216,7 +216,7 @@ module AssignmentOverrideApplicator
def self.observer_overrides(assignment_or_quiz, user)
context = assignment_or_quiz.context
observed_students = ObserverEnrollment.observed_students(context, user)
observed_student_overrides = observed_students.map do |student, enrollments|
observed_student_overrides = observed_students.each_key.map do |student|
overrides_for_assignment_and_user(assignment_or_quiz, student)
end
observed_student_overrides.flatten.uniq

View File

@ -262,8 +262,7 @@ module AuthenticationMethods
end
if request_become_user && request_become_user.id != session[:become_user_id].to_i && request_become_user.can_masquerade?(@current_user, @domain_root_account)
params_without_become = params.dup
params_without_become.delete_if { |k, v| ['become_user_id', 'become_teacher', 'become_student', 'me'].include? k }
params_without_become = params.except('become_user_id', 'become_teacher', 'become_student', 'me')
params_without_become[:only_path] = true
session[:masquerade_return_to] = url_for(params_without_become.to_unsafe_h)
return redirect_to user_masquerade_url(request_become_user.id)

View File

@ -123,12 +123,12 @@ module CC::Importer
def check_for_unescaped_url_properties(obj)
# Recursively look for properties named 'url'
if obj.is_a?(Hash)
obj.select { |k, v| k.to_s == 'url' && v.is_a?(String) }.each do |k, v|
check_for_unescaped_url(v)
end
obj.each { |k, v| check_for_unescaped_url_properties(v) }
elsif obj.is_a?(Array)
case obj
when Hash
obj.select { |k, v| k.to_s == 'url' && v.is_a?(String) }
.each_value { |v| check_for_unescaped_url(v) }
obj.each_value { |v| check_for_unescaped_url_properties(v) }
when Array
obj.each { |o| check_for_unescaped_url_properties(o) }
end
end

View File

@ -424,7 +424,7 @@ module CC
unless answer['comments'].blank? && answer['comments_html'].blank?
node.respcondition do |r_node|
r_node.conditionvar do |c_node|
c_node.not do |n_node|
c_node.not do
c_node.varequal(answer['match_id'], :respident => "response_#{answer['id']}")
end
end

View File

@ -161,7 +161,7 @@ class CourseLinkValidator
end
end
(question.question_data[:answers] || []).each_with_index do |answer, i|
(question.question_data[:answers] || []).each do |answer|
[:html, :comments_html, :left_html].each do |field|
find_invalid_links(answer[field]) do |field_links|
links += field_links

View File

@ -33,7 +33,7 @@ module CustomValidations
end
def validates_as_readonly(*fields)
validates_each(fields) do |record, attr, value|
validates_each(fields) do |record, attr, _value|
if !record.new_record? && record.send("#{attr}_changed?")
record.errors.add attr, "cannot be changed"
end

View File

@ -30,7 +30,7 @@ module DataFixup::CopyRoleOverrides
}
dup = RoleOverride.new
old_role_override.attributes.delete_if { |k, v| [:id, :permission, :created_at, :updated_at].include?(k.to_sym) }.each do |key, val|
old_role_override.attributes.except("id", "permission", "created_at", "updated_at").each do |key, val|
dup.send("#{key}=", val)
end
dup.permission = new_permission.to_s

View File

@ -22,13 +22,13 @@ module DataFixup::DeleteInvalidCommunicationChannels
def self.run
scope = CommunicationChannel.where(path_type: CommunicationChannel::TYPE_EMAIL)
scope.find_ids_in_ranges(batch_size: 10000) do |min_id, max_id|
records = scope.where(id: min_id..max_id).pluck(:id, :user_id, :path).reject do |id, user_id, path|
records = scope.where(id: min_id..max_id).pluck(:id, :user_id, :path).reject do |_id, _user_id, path|
EmailAddressValidator.valid?(path)
end
# We have a number of email addresses in the system that are valid except
# for leading or trailing whitespace.
r1, r2 = records.partition do |id, user_id, path|
r1, r2 = records.partition do |_id, _user_id, path|
EmailAddressValidator.valid?(path.strip)
end

View File

@ -546,7 +546,7 @@ class GradebookImporter
def process_submissions(row, student)
importer_submissions = []
@assignments.each_with_index do |assignment, idx|
@assignments.each do |assignment|
assignment_id = assignment.new_record? ? assignment.id : assignment.previous_id
assignment_index = @assignment_indices[assignment.id]
grade = row[assignment_index]&.strip

View File

@ -83,12 +83,12 @@ module LocaleSelection
# then i should get 'es' (en and en-US ranges both match en-US, and
# en-US range is a longer match, so it loses)
best_locales = supported_locales.inject([]) { |ary, locale|
if (best_range = ranges.detect { |r, q| r + '-' == (locale.downcase + '-')[0..r.size] || r == '*' })
ary << [locale, best_range.last, ranges.index(best_range)] unless best_range.last == 0
best_locales = supported_locales.filter_map do |locale|
if (best_range = ranges.detect { |r, _q| "#{r}-" == ("#{locale.downcase}-")[0..r.size] || r == '*' }) &&
best_range.last != 0
[locale, best_range.last, ranges.index(best_range)]
end
ary
}.sort_by { |l, q, pos| [-q, pos, l.count('-'), l] }
end.sort_by { |l, q, pos| [-q, pos, l.count('-'), l] }
# wrt the sorting here, rfc2616 doesn't specify which tag is preferable
# if there is a quality tie (due to prefix matching or otherwise).
# technically they are equally acceptable. we've decided to break ties
@ -115,7 +115,7 @@ module LocaleSelection
def available_locales
result = {}
settings = Canvas::Plugin.find(:i18n).settings || {}
enabled_custom_locales = settings.select { |locale, enabled| enabled }.map(&:first).map(&:to_sym)
enabled_custom_locales = settings.select { |_locale, enabled| enabled }.keys.map(&:to_sym)
I18n.available_locales.each do |locale|
name = I18n.send(:t, :locales, :locale => locale)[locale]
custom = I18n.send(:t, :custom, locale: locale) == true

View File

@ -120,7 +120,7 @@ class SubmissionList
# puts "----------------------------------------------"
# puts "starting"
# puts "---------------------------------------------------------------------------------"
self.list.map do |day, value|
self.list.map do |day, _value|
# puts "-----------------------------------------------item #{Time.now - current}----------------------------"
# current = Time.now
OpenObject.new(:date => day, :graders => graders_for_day(day))
@ -221,7 +221,7 @@ class SubmissionList
# makes our final product much more yummy.
def trim_keys(list)
list.each do |hsh|
hsh.delete_if { |key, v| !VALID_KEYS.include?(key) }
hsh.slice!(*VALID_KEYS)
end
end

View File

@ -22,7 +22,7 @@ unless $canvas_tasks_loaded
namespace :canvas do
desc "Compile javascript and css assets."
task :compile_assets do |t, args|
task :compile_assets do # rubocop:disable Rails/RakeEnvironment
# running :environment as a prerequisite task is necessary even if we don't
# need it for this task: forked processes (through Parallel) that invoke other
# Rake tasks may require the Rails environment and for some reason, Rake will

View File

@ -3,7 +3,7 @@
namespace :canvas do
namespace :quizzes do
desc 'Generate events from snapshots for submissions to a quiz.'
task :generate_events_from_snapshots, [:quiz_id] => :environment do |t, args|
task :generate_events_from_snapshots, [:quiz_id] => :environment do |_t, args|
quiz_id = Array(args[:quiz_id])
quiz_submission_ids = Quizzes::QuizSubmission.where(quiz_id: quiz_id)
@ -23,7 +23,7 @@ namespace :canvas do
end # task :generate_events_from_snapshots
desc "Generate a JSON dump of events in a single quiz submission."
task :dump_events, [:quiz_submission_id, :out] => :environment do |t, args|
task :dump_events, [:quiz_submission_id, :out] => :environment do |_t, args|
require 'json'
require 'benchmark'
@ -61,7 +61,7 @@ namespace :canvas do
end
desc 'Create partition tables for the current and upcoming months.'
task :create_event_partitions => :environment do |t, args|
task :create_event_partitions => :environment do
Shard.with_each_shard do
Quizzes::QuizSubmissionEventPartitioner.logger = Logger.new(STDOUT)
Quizzes::QuizSubmissionEventPartitioner.process

View File

@ -2,7 +2,7 @@
namespace :db do
desc "migrate the page views in the database to cassandra"
task :migrate_pageviews_to_cassandra, [:shard_id] => :environment do |t, args|
task :migrate_pageviews_to_cassandra, [:shard_id] => :environment do |_t, args|
shard = Shard.birth
if args[:shard_id]
shard = Shard.find(args[:shard_id])

View File

@ -39,7 +39,8 @@ begin
# t.options << '--debug'
end
task 'api' do |t|
desc "generate API docs"
task 'api' do # rubocop:disable Rails/RakeEnvironment
puts "API Documentation successfully generated in #{DOC_DIR}\n" \
"See #{DOC_DIR}/index.html"
end

View File

@ -211,7 +211,7 @@ module UserContent
def translate_content(html)
return html if html.blank?
asset_types = AssetTypes.reject { |k, v| !@allowed_types.include?(k) }
asset_types = AssetTypes.slice(*@allowed_types)
html.gsub(@toplevel_regex) do |url|
_absolute_part, prefix, type, obj_id, rest = [$1, $2, $3, $4, $5]

View File

@ -62,7 +62,7 @@ class UserList
def as_json(**)
{
:users => addresses.map { |a| a.reject { |k, v| k == :shard } },
:users => addresses.map { |a| a.except(:shard) },
:duplicates => duplicate_addresses,
:errored_users => errors
}