RuboCop: Lint/AssignmentInCondition

[skip-stages=Flakey]

(manual)

Change-Id: I855b13a7888f4926df42fe6306cc248e611efdf6
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/274712
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-09-28 18:07:43 -06:00
parent dbd8c46655
commit 58d528037e
90 changed files with 309 additions and 317 deletions

View File

@ -37,6 +37,8 @@ Lint/AmbiguousOperatorPrecedence:
Severity: error Severity: error
Lint/AmbiguousRegexpLiteral: Lint/AmbiguousRegexpLiteral:
Severity: error Severity: error
Lint/AssignmentInCondition:
Severity: error
Lint/Debugger: Lint/Debugger:
Severity: error Severity: error
Lint/DeprecatedClassMethods: Lint/DeprecatedClassMethods:

View File

@ -66,7 +66,7 @@ module Moodle
def add_warnings_to_map(warning_map) def add_warnings_to_map(warning_map)
warning_map.values.each do |warnings| warning_map.values.each do |warnings|
if hashes = warnings['multiple_dropdowns_question'] if (hashes = warnings['multiple_dropdowns_question'])
if hashes.count > 2 if hashes.count > 2
q_hash = hashes.first q_hash = hashes.first
q_hash['import_warnings'] ||= [] q_hash['import_warnings'] ||= []
@ -82,7 +82,7 @@ module Moodle
end end
end end
if hashes = warnings['calculated_question'] if (hashes = warnings['calculated_question'])
if hashes.count > 2 if hashes.count > 2
q_hash = hashes.first q_hash = hashes.first
q_hash['import_warnings'] ||= [] q_hash['import_warnings'] ||= []

View File

@ -62,7 +62,7 @@ module Canvas::Migration
cm.update_conversion_progress(100) cm.update_conversion_progress(100)
cm.migration_settings[:migration_ids_to_import] = { :copy => { :everything => true } }.merge(cm.migration_settings[:migration_ids_to_import] || {}) cm.migration_settings[:migration_ids_to_import] = { :copy => { :everything => true } }.merge(cm.migration_settings[:migration_ids_to_import] || {})
if path = converter.course[:files_import_root_path] if (path = converter.course[:files_import_root_path])
cm.migration_settings[:files_import_root_path] = path cm.migration_settings[:files_import_root_path] = path
end end
cm.save cm.save

View File

@ -39,7 +39,7 @@ module Qti
end end
def self.qti_enabled? def self.qti_enabled?
if plugin = Canvas::Plugin.find(:qti_converter) if (plugin = Canvas::Plugin.find(:qti_converter))
return plugin.settings[:enabled].to_s == 'true' return plugin.settings[:enabled].to_s == 'true'
end end
@ -54,7 +54,7 @@ module Qti
end end
def self.convert_questions(manifest_path, opts = {}) def self.convert_questions(manifest_path, opts = {})
if path_map = opts[:file_path_map] if (path_map = opts[:file_path_map])
# used when searching for matching file paths to help find the best matching path # used when searching for matching file paths to help find the best matching path
sorted_paths = path_map.keys.sort_by { |v| v.length } sorted_paths = path_map.keys.sort_by { |v| v.length }
else else

View File

@ -40,7 +40,7 @@ module Qti
@doc = nil @doc = nil
@flavor = opts[:flavor] @flavor = opts[:flavor]
@opts = opts @opts = opts
if @path_map = opts[:file_path_map] if (@path_map = opts[:file_path_map])
@sorted_paths = opts[:sorted_file_paths] @sorted_paths = opts[:sorted_file_paths]
@sorted_paths ||= @path_map.keys.sort_by { |v| v.length } @sorted_paths ||= @path_map.keys.sort_by { |v| v.length }
end end
@ -49,7 +49,8 @@ module Qti
@package_root = PackageRoot.new(opts[:base_dir]) @package_root = PackageRoot.new(opts[:base_dir])
@identifier = @manifest_node['identifier'] @identifier = @manifest_node['identifier']
@href = @package_root.item_path(@manifest_node['href']) @href = @package_root.item_path(@manifest_node['href'])
if title = @manifest_node.at_css('title langstring') || title = @manifest_node.at_css('xmlns|title xmlns|langstring', 'xmlns' => Qti::Converter::IMS_MD) if (title = @manifest_node.at_css('title langstring') ||
@manifest_node.at_css('xmlns|title xmlns|langstring', 'xmlns' => Qti::Converter::IMS_MD))
@title = title.text @title = title.text
end end
else else
@ -133,10 +134,13 @@ module Qti
end end
elsif @doc.at_css('itemBody associateInteraction prompt') elsif @doc.at_css('itemBody associateInteraction prompt')
@question[:question_text] = "" # apparently they deliberately had a blank question? @question[:question_text] = "" # apparently they deliberately had a blank question?
elsif text = @doc.at_css('itemBody div:first-child') || @doc.at_css('itemBody p:first-child') || @doc.at_css('itemBody div') || @doc.at_css('itemBody p') elsif (text = @doc.at_css('itemBody div:first-child') ||
@doc.at_css('itemBody p:first-child') ||
@doc.at_css('itemBody div') ||
@doc.at_css('itemBody p'))
@question[:question_text] = sanitize_html!(text) @question[:question_text] = sanitize_html!(text)
elsif @doc.at_css('itemBody') elsif @doc.at_css('itemBody')
if text = @doc.at_css('itemBody').children.find { |c| c.text.strip != '' } if (text = @doc.at_css('itemBody').children.find { |c| c.text.strip != '' })
@question[:question_text] = sanitize_html_string(text.text) @question[:question_text] = sanitize_html_string(text.text)
end end
end end
@ -171,32 +175,32 @@ module Qti
} }
def parse_instructure_metadata def parse_instructure_metadata
if meta = @doc.at_css('instructureMetadata') if (meta = @doc.at_css('instructureMetadata'))
if bank = get_node_att(meta, 'instructureField[name=question_bank]', 'value') if (bank = get_node_att(meta, 'instructureField[name=question_bank]', 'value'))
@question[:question_bank_name] = bank @question[:question_bank_name] = bank
end end
if bank = get_node_att(meta, 'instructureField[name=question_bank_iden]', 'value') if (bank = get_node_att(meta, 'instructureField[name=question_bank_iden]', 'value'))
@question[:question_bank_id] = bank @question[:question_bank_id] = bank
if bb_bank = get_node_att(meta, 'instructureField[name=bb_question_bank_iden]', 'value') if (bb_bank = get_node_att(meta, 'instructureField[name=bb_question_bank_iden]', 'value'))
@question[:bb_question_bank_id] = bb_bank @question[:bb_question_bank_id] = bb_bank
end end
end end
if score = get_node_att(meta, 'instructureField[name=max_score]', 'value') if (score = get_node_att(meta, 'instructureField[name=max_score]', 'value'))
@question[:points_possible] = [score.to_f, 0.0].max @question[:points_possible] = [score.to_f, 0.0].max
end end
if score = get_node_att(meta, 'instructureField[name=points_possible]', 'value') if (score = get_node_att(meta, 'instructureField[name=points_possible]', 'value'))
@question[:points_possible] = [score.to_f, 0.0].max @question[:points_possible] = [score.to_f, 0.0].max
end end
if ref = get_node_att(meta, 'instructureField[name=assessment_question_identifierref]', 'value') if (ref = get_node_att(meta, 'instructureField[name=assessment_question_identifierref]', 'value'))
@question[:assessment_question_migration_id] = ref @question[:assessment_question_migration_id] = ref
end end
if ref = get_node_att(meta, 'instructureField[name=original_answer_ids]', 'value') if (ref = get_node_att(meta, 'instructureField[name=original_answer_ids]', 'value'))
@original_answer_ids = ref.split(",") @original_answer_ids = ref.split(",")
end end
if get_node_att(meta, 'instructureField[name=cc_profile]', 'value') == 'cc.pattern_match.v0p1' if get_node_att(meta, 'instructureField[name=cc_profile]', 'value') == 'cc.pattern_match.v0p1'
@question[:is_cc_pattern_match] = true @question[:is_cc_pattern_match] = true
end end
if type = get_node_att(meta, 'instructureField[name=bb_question_type]', 'value') if (type = get_node_att(meta, 'instructureField[name=bb_question_type]', 'value'))
@migration_type = type @migration_type = type
case @migration_type case @migration_type
when 'True/False' when 'True/False'
@ -218,7 +222,7 @@ module Qti
when 'Essay' when 'Essay'
@question[:question_type] = 'essay_question' @question[:question_type] = 'essay_question'
end end
elsif type = get_node_att(meta, 'instructureField[name=question_type]', 'value') elsif (type = get_node_att(meta, 'instructureField[name=question_type]', 'value'))
@migration_type = type @migration_type = type
QUESTION_TYPE_MAPPING.each do |k, v| QUESTION_TYPE_MAPPING.each do |k, v|
@migration_type = v if k === @migration_type @migration_type = v if k === @migration_type
@ -273,7 +277,7 @@ module Qti
elsif (@flavor == Qti::Flavors::D2L && f.text.present?) || id =~ /general_|_all/i elsif (@flavor == Qti::Flavors::D2L && f.text.present?) || id =~ /general_|_all/i
extract_feedback!(@question, :neutral_comments, f) extract_feedback!(@question, :neutral_comments, f)
elsif id =~ /feedback_(\d*)_fb/i elsif id =~ /feedback_(\d*)_fb/i
if answer = @question[:answers].find { |a| a[:migration_id] == "RESPONSE_#{$1}" } if (answer = @question[:answers].find { |a| a[:migration_id] == "RESPONSE_#{$1}" })
extract_feedback!(answer, :comments, f) extract_feedback!(answer, :comments, f)
end end
end end
@ -309,13 +313,13 @@ module Qti
manifest_node = opts[:manifest_node] manifest_node = opts[:manifest_node]
if manifest_node if manifest_node
if type = get_interaction_type(manifest_node) if (type = get_interaction_type(manifest_node))
opts[:interaction_type] ||= type.text.downcase opts[:interaction_type] ||= type.text.downcase
end end
if type = get_node_att(manifest_node, 'instructureMetadata instructureField[name=bb_question_type]', 'value') if (type = get_node_att(manifest_node, 'instructureMetadata instructureField[name=bb_question_type]', 'value'))
opts[:custom_type] ||= type.downcase opts[:custom_type] ||= type.downcase
end end
if type = get_node_att(manifest_node, 'instructureMetadata instructureField[name=question_type]', 'value') if (type = get_node_att(manifest_node, 'instructureMetadata instructureField[name=question_type]', 'value'))
type = type.downcase type = type.downcase
opts[:custom_type] ||= type opts[:custom_type] ||= type
if type == 'matching_question' if type == 'matching_question'
@ -396,9 +400,9 @@ module Qti
def get_feedback_id(cond) def get_feedback_id(cond)
id = nil id = nil
if feedback = cond.at_css('setOutcomeValue[identifier=FEEDBACK]') if (feedback = cond.at_css('setOutcomeValue[identifier=FEEDBACK]'))
if feedback.at_css('variable[identifier=FEEDBACK]') if feedback.at_css('variable[identifier=FEEDBACK]')
if feedback = feedback.at_css('baseValue[baseType=identifier]') if (feedback = feedback.at_css('baseValue[baseType=identifier]'))
id = feedback.text.strip id = feedback.text.strip
end end
end end

View File

@ -45,11 +45,12 @@ module Qti
def create_instructure_quiz def create_instructure_quiz
begin begin
# Get manifest data # Get manifest data
if md = @manifest_node.at_css("instructureMetadata") if (md = @manifest_node.at_css("instructureMetadata"))
if item = get_node_att(md, 'instructureField[name=show_score]', 'value') if (item = get_node_att(md, 'instructureField[name=show_score]', 'value'))
@quiz[:show_score] = item =~ /true/i ? true : false @quiz[:show_score] = item =~ /true/i ? true : false
end end
if item = get_node_att(md, 'instructureField[name=quiz_type]', 'value') || item = get_node_att(md, 'instructureField[name=bb8_assessment_type]', 'value') if (item = get_node_att(md, 'instructureField[name=quiz_type]', 'value') ||
get_node_att(md, 'instructureField[name=bb8_assessment_type]', 'value'))
# known possible values: Self-assessment, Survey, Examination (practice is instructure default) # known possible values: Self-assessment, Survey, Examination (practice is instructure default)
# BB8: Test, Pool # BB8: Test, Pool
@quiz[:quiz_type] = "assignment" if item =~ /examination|test|quiz/i @quiz[:quiz_type] = "assignment" if item =~ /examination|test|quiz/i
@ -58,14 +59,14 @@ module Qti
return nil return nil
end end
end end
if item = get_node_att(md, 'instructureField[name=which_attempt_to_keep]', 'value') if (item = get_node_att(md, 'instructureField[name=which_attempt_to_keep]', 'value'))
# known possible values: Highest, First, Last (highest is instructure default) # known possible values: Highest, First, Last (highest is instructure default)
@quiz[:which_attempt_to_keep] = "keep_latest" if item =~ /last/i @quiz[:which_attempt_to_keep] = "keep_latest" if item =~ /last/i
end end
if item = get_node_att(md, 'instructureField[name=max_score]', 'value') if (item = get_node_att(md, 'instructureField[name=max_score]', 'value'))
@quiz[:points_possible] = item @quiz[:points_possible] = item
end end
if item = get_node_att(md, 'instructureField[name=bb8_object_id]', 'value') if (item = get_node_att(md, 'instructureField[name=bb8_object_id]', 'value'))
@quiz[:alternate_migration_id] = item @quiz[:alternate_migration_id] = item
end end
end end
@ -94,23 +95,22 @@ module Qti
end end
def parse_instructure_metadata(doc) def parse_instructure_metadata(doc)
if meta = doc.at_css('instructureMetadata') if (meta = doc.at_css('instructureMetadata'))
if password = get_node_att(meta, 'instructureField[name=password]', 'value') if (password = get_node_att(meta, 'instructureField[name=password]', 'value'))
@quiz[:access_code] = password @quiz[:access_code] = password
end end
if id = get_node_att(meta, 'instructureField[name=assignment_identifierref]', 'value') if (id = get_node_att(meta, 'instructureField[name=assignment_identifierref]', 'value'))
@quiz[:assignment_migration_id] = id @quiz[:assignment_migration_id] = id
end end
if @opts[:flavor] == Qti::Flavors::D2L if @opts[:flavor] == Qti::Flavors::D2L
if intro = get_node_att(meta, 'instructureField[name=d2l_intro_message]', 'value') if (intro = get_node_att(meta, 'instructureField[name=d2l_intro_message]', 'value'))
@quiz[:questions].unshift({ :question_type => 'text_only_question', :question_text => intro, :migration_id => unique_local_id }) @quiz[:questions].unshift({ :question_type => 'text_only_question', :question_text => intro, :migration_id => unique_local_id })
end end
if html = get_node_att(meta, 'instructureField[name=assessment_rubric_html]', 'value') if (html = get_node_att(meta, 'instructureField[name=assessment_rubric_html]', 'value')) &&
if node = (Nokogiri::HTML5.fragment(html) rescue nil) (node = (Nokogiri::HTML5.fragment(html) rescue nil))
description = sanitize_html_string(node.text) description = sanitize_html_string(node.text)
@quiz[:description] = description if description.present? @quiz[:description] = description if description.present?
end
end end
end end
end end
@ -120,20 +120,19 @@ module Qti
@quiz[:title] = @title || get_node_att(doc, 'assessmentTest', 'title') @quiz[:title] = @title || get_node_att(doc, 'assessmentTest', 'title')
@quiz[:quiz_name] = @quiz[:title] @quiz[:quiz_name] = @quiz[:title]
@quiz[:migration_id] = get_node_att(doc, 'assessmentTest', 'identifier') @quiz[:migration_id] = get_node_att(doc, 'assessmentTest', 'identifier')
if limit = doc.at_css('timeLimits') if (limit = doc.at_css('timeLimits'))
@quiz[:time_limit] = AssessmentTestConverter.parse_time_limit(limit['maxTime']) @quiz[:time_limit] = AssessmentTestConverter.parse_time_limit(limit['maxTime'])
end end
if part = doc.at_css('testPart[identifier=BaseTestPart]') || doc.at_css('testPart') if (part = doc.at_css('testPart[identifier=BaseTestPart]') || doc.at_css('testPart'))
if control = part.at_css('itemSessionControl') if (control = part.at_css('itemSessionControl'))
if max = control['maxAttempts'] if (max = control['maxAttempts'])
max = -1 if max =~ /unlimited/i max = -1 if max =~ /unlimited/i
max = max.to_i max = max.to_i
# -1 means no limit in instructure, 0 means no limit in QTI # -1 means no limit in instructure, 0 means no limit in QTI
@quiz[:allowed_attempts] = max >= 1 ? max : -1 @quiz[:allowed_attempts] = max >= 1 ? max : -1
end end
if show = control['showSolution'] if (show = control['showSolution'])
show = show @quiz[:show_correct_answers] = show.downcase == "true"
@quiz[:show_correct_answers] = show.downcase == "true" ? true : false
end end
end end
@ -173,15 +172,15 @@ module Qti
group = nil group = nil
questions_list = @quiz[:questions] questions_list = @quiz[:questions]
if shuffle = get_node_att(section, 'ordering', 'shuffle') if (shuffle = get_node_att(section, 'ordering', 'shuffle'))
@quiz[:shuffle_answers] = true if shuffle =~ /true/i @quiz[:shuffle_answers] = true if shuffle =~ /true/i
end end
if select = AssessmentTestConverter.parse_pick_count(section) if (select = AssessmentTestConverter.parse_pick_count(section))
group = { :questions => [], :pick_count => select, :question_type => 'question_group', :title => section['title'] } group = { :questions => [], :pick_count => select, :question_type => 'question_group', :title => section['title'] }
if weight = get_node_att(section, 'weight', 'value') if (weight = get_node_att(section, 'weight', 'value'))
group[:question_points] = convert_weight_to_points(weight) group[:question_points] = convert_weight_to_points(weight)
end end
if val = get_float_val(section, 'points_per_item') if (val = get_float_val(section, 'points_per_item'))
group[:question_points] = val group[:question_points] = val
end end
bank_refs = section.css('sourcebank_ref') bank_refs = section.css('sourcebank_ref')
@ -191,17 +190,17 @@ module Qti
elsif bank_refs.count == 1 elsif bank_refs.count == 1
group[:question_bank_migration_id] = translate_bank_id(bank_refs.first.text) group[:question_bank_migration_id] = translate_bank_id(bank_refs.first.text)
end end
if val = get_node_val(section, 'sourcebank_context') if (val = get_node_val(section, 'sourcebank_context'))
group[:question_bank_context] = val group[:question_bank_context] = val
end end
if val = get_bool_val(section, 'sourcebank_is_external') if (val = get_bool_val(section, 'sourcebank_is_external'))
group[:question_bank_is_external] = val group[:question_bank_is_external] = val
end end
group[:migration_id] = section['identifier'] && section['identifier'] != "" ? section['identifier'] : unique_local_id group[:migration_id] = section['identifier'] && section['identifier'] != "" ? section['identifier'] : unique_local_id
questions_list = group[:questions] questions_list = group[:questions]
end end
if section['visible'] and section['visible'] =~ /true/i if section['visible'] and section['visible'] =~ /true/i
if title = section['title'] if (title = section['title'])
# Create an empty question with a title in it # Create an empty question with a title in it
@quiz[:questions] << { :question_type => 'text_only_question', :question_text => title, :migration_id => unique_local_id } @quiz[:questions] << { :question_type => 'text_only_question', :question_text => title, :migration_id => unique_local_id }
end end
@ -265,7 +264,7 @@ module Qti
if @opts[:flavor] == Qti::Flavors::D2L && item_ref['label'].present? if @opts[:flavor] == Qti::Flavors::D2L && item_ref['label'].present?
question[:migration_id] = item_ref['label'] question[:migration_id] = item_ref['label']
end end
if weight = get_node_att(item_ref, 'weight', 'value') if (weight = get_node_att(item_ref, 'weight', 'value'))
question[:points_possible] = convert_weight_to_points(weight) question[:points_possible] = convert_weight_to_points(weight)
end end
end end

View File

@ -35,13 +35,13 @@ module Qti
if @doc.at_css('associateInteraction') if @doc.at_css('associateInteraction')
match_map = {} match_map = {}
get_all_matches_with_interaction(match_map) get_all_matches_with_interaction(match_map)
if pair_node = @doc.at_css('responseDeclaration[baseType=pair][cardinality=multiple]') if (pair_node = @doc.at_css('responseDeclaration[baseType=pair][cardinality=multiple]'))
get_answers_from_matching_pairs(pair_node, match_map) get_answers_from_matching_pairs(pair_node, match_map)
else else
get_all_answers_with_interaction(match_map) get_all_answers_with_interaction(match_map)
check_for_meta_matches check_for_meta_matches
end end
elsif node = @doc.at_css('matchInteraction') elsif (node = @doc.at_css('matchInteraction'))
get_all_match_interaction(node) get_all_match_interaction(node)
elsif @custom_type == 'respondus_matching' elsif @custom_type == 'respondus_matching'
get_respondus_answers get_respondus_answers
@ -71,10 +71,10 @@ module Qti
@question[:answers].each do |answer| @question[:answers].each do |answer|
answer[:left] = answer[:text] if answer[:text].present? answer[:left] = answer[:text] if answer[:text].present?
answer[:left_html] = answer[:html] if answer[:html].present? answer[:left_html] = answer[:html] if answer[:html].present?
if answer[:match_id] if answer[:match_id] &&
if @question[:matches] && match = @question[:matches].find { |m| m[:match_id] == answer[:match_id] } @question[:matches] &&
answer[:right] = match[:text] (match = @question[:matches].find { |m| m[:match_id] == answer[:match_id] })
end answer[:right] = match[:text]
end end
end end
@ -110,18 +110,16 @@ module Qti
end end
def get_canvas_matches(match_map) def get_canvas_matches(match_map)
if ci = @doc.at_css('choiceInteraction') @doc.at_css('choiceInteraction')&.css('simpleChoice')&.each do |sc|
ci.css('simpleChoice').each do |sc| match = {}
match = {} @question[:matches] << match
@question[:matches] << match match_map[sc['identifier']] = match
match_map[sc['identifier']] = match if sc['identifier'] =~ /(\d+)/
if sc['identifier'] =~ /(\d+)/ match[:match_id] = $1.to_i
match[:match_id] = $1.to_i else
else match[:match_id] = unique_local_id
match[:match_id] = unique_local_id
end
match[:text] = sc.text.strip
end end
match[:text] = sc.text.strip
end end
end end
@ -139,13 +137,13 @@ module Qti
@doc.css('responseIf, responseElseIf').each do |r_if| @doc.css('responseIf, responseElseIf').each do |r_if|
answer_mig_id = nil answer_mig_id = nil
match_mig_id = nil match_mig_id = nil
if match = r_if.at_css('match') if (match = r_if.at_css('match'))
answer_mig_id = get_node_att(match, 'variable', 'identifier') answer_mig_id = get_node_att(match, 'variable', 'identifier')
match_mig_id = match.at_css('baseValue[baseType=identifier]').text rescue nil match_mig_id = match.at_css('baseValue[baseType=identifier]').text rescue nil
end end
if answer = answer_map[answer_mig_id] if (answer = answer_map[answer_mig_id])
answer[:feedback_id] = get_feedback_id(r_if) answer[:feedback_id] = get_feedback_id(r_if)
if r_if.at_css('setOutcomeValue[identifier=SCORE] sum') && match = match_map[match_mig_id] if r_if.at_css('setOutcomeValue[identifier=SCORE] sum') && (match = match_map[match_mig_id])
answer[:match_id] = match[:match_id] answer[:match_id] = match[:match_id]
end end
end end
@ -190,7 +188,7 @@ module Qti
end end
def get_all_matches_from_body def get_all_matches_from_body
if matches = @doc.at_css('div.RIGHT_MATCH_BLOCK') if (matches = @doc.at_css('div.RIGHT_MATCH_BLOCK'))
matches.css('div').each do |m| matches.css('div').each do |m|
match = {} match = {}
@question[:matches] << match @question[:matches] << match
@ -260,7 +258,7 @@ module Qti
match = {} match = {}
extract_answer!(match, m) extract_answer!(match, m)
if other_match = @question[:matches].detect { |om| match[:text].to_s.strip == om[:text].to_s.strip && match[:html].to_s.strip == om[:html].to_s.strip } if (other_match = @question[:matches].detect { |om| match[:text].to_s.strip == om[:text].to_s.strip && match[:html].to_s.strip == om[:html].to_s.strip })
match_map[m['identifier']] = other_match[:match_id] match_map[m['identifier']] = other_match[:match_id]
else else
@question[:matches] << match @question[:matches] << match
@ -281,9 +279,9 @@ module Qti
answer[:id] = unique_local_id answer[:id] = unique_local_id
answer[:comments] = "" answer[:comments] = ""
if option = a.at_css('simpleAssociableChoice[identifier^=MATCH]') if (option = a.at_css('simpleAssociableChoice[identifier^=MATCH]'))
answer[:match_id] = match_map[option.text.strip] answer[:match_id] = match_map[option.text.strip]
elsif resp_id = a['responseIdentifier'] elsif (resp_id = a['responseIdentifier'])
@doc.css("match variable[identifier=#{resp_id}]").each do |variable| @doc.css("match variable[identifier=#{resp_id}]").each do |variable|
match = variable.parent match = variable.parent
response_if = match.parent response_if = match.parent
@ -314,7 +312,7 @@ module Qti
# Replaces the matches with their full-text instead of a,b,c/1,2,3/etc. # Replaces the matches with their full-text instead of a,b,c/1,2,3/etc.
def check_for_meta_matches def check_for_meta_matches
if long_matches = @doc.search('instructureMetadata matchingMatch') if (long_matches = @doc.search('instructureMetadata matchingMatch'))
@question[:matches].each_with_index do |match, i| @question[:matches].each_with_index do |match, i|
match[:text] = long_matches[i].text.strip.gsub(/ +/, " ") if long_matches[i] match[:text] = long_matches[i].text.strip.gsub(/ +/, " ") if long_matches[i]
end end
@ -348,7 +346,7 @@ module Qti
# Check if there are correct answers explicitly specified # Check if there are correct answers explicitly specified
@doc.css('correctResponse > value').each do |match| @doc.css('correctResponse > value').each do |match|
answer_id, match_id = match.text.split answer_id, match_id = match.text.split
if answer = answer_map[answer_id.strip] and m = match_map[match_id.strip] if (answer = answer_map[answer_id.strip]) && (m = match_map[match_id.strip])
answer[:match_id] = m[:match_id] answer[:match_id] = m[:match_id]
end end
end end

View File

@ -50,10 +50,12 @@ module Qti
get_feedback() get_feedback()
get_formulas() get_formulas()
if !@question[:answer_tolerance] && tolerance = get_node_att(@doc, 'instructureMetadata instructureField[name=formula_tolerance]', 'value') if !@question[:answer_tolerance] &&
(tolerance = get_node_att(@doc, 'instructureMetadata instructureField[name=formula_tolerance]', 'value'))
@question[:answer_tolerance] = tolerance @question[:answer_tolerance] = tolerance
end end
if !@question[:formula_decimal_places] && precision = get_node_att(@doc, 'instructureMetadata instructureField[name=formula_precision]', 'value') if !@question[:formula_decimal_places] &&
(precision = get_node_att(@doc, 'instructureMetadata instructureField[name=formula_precision]', 'value'))
@question[:formula_decimal_places] = precision.to_i @question[:formula_decimal_places] = precision.to_i
end end
@ -101,7 +103,7 @@ module Qti
def get_formulas def get_formulas
@question[:formulas] = [] @question[:formulas] = []
if formulas_node = @doc.at_css('formulas') if (formulas_node = @doc.at_css('formulas'))
@question[:formula_decimal_places] = formulas_node['decimal_places'].to_i @question[:formula_decimal_places] = formulas_node['decimal_places'].to_i
formulas_node.css('formula').each do |f_node| formulas_node.css('formula').each do |f_node|
formula = {} formula = {}

View File

@ -113,7 +113,7 @@ module Qti
answer[:migration_id] = choice['identifier'] answer[:migration_id] = choice['identifier']
answer[:id] = get_or_generate_answer_id(answer[:migration_id]) answer[:id] = get_or_generate_answer_id(answer[:migration_id])
if feedback = choice.at_css('feedbackInline') if (feedback = choice.at_css('feedbackInline'))
# weird Angel feedback # weird Angel feedback
answer[:text] = choice.children.first.text.strip answer[:text] = choice.children.first.text.strip
answer[:comments] = feedback.text.strip answer[:comments] = feedback.text.strip
@ -238,7 +238,7 @@ module Qti
# Check if there are correct answers explicitly specified # Check if there are correct answers explicitly specified
@doc.css('correctResponse > value, correctResponse > Value').each do |correct_id| @doc.css('correctResponse > value, correctResponse > Value').each do |correct_id|
correct_id = correct_id.text if correct_id correct_id = correct_id.text if correct_id
if correct_id && answer = answers_hash[correct_id] if correct_id && (answer = answers_hash[correct_id])
answer[:weight] = DEFAULT_CORRECT_WEIGHT answer[:weight] = DEFAULT_CORRECT_WEIGHT
end end
end end
@ -248,16 +248,12 @@ module Qti
def get_response_weight(cond) def get_response_weight(cond)
weight = AssessmentItemConverter::DEFAULT_INCORRECT_WEIGHT weight = AssessmentItemConverter::DEFAULT_INCORRECT_WEIGHT
if sum = cond.at_css('setOutcomeValue[identifier=SCORE] sum baseValue[baseType]') if (base = cond.at_css('setOutcomeValue[identifier=SCORE] sum baseValue[baseType]')) ||
(base = cond.at_css('setOutcomeValue[identifier=D2L_CORRECT] sum baseValue[baseType]')) ||
(base = cond.at_css('setOutcomeValue[identifier=SCORE] > baseValue[baseType]')) ||
(base = cond.at_css('setOutcomeValue[identifier^=SCORE] baseValue[baseType]')) ||
(base = cond.at_css('setOutcomeValue[identifier$=SCORE] baseValue[baseType]'))
# it'll only be true if the score is a sum > 0 # it'll only be true if the score is a sum > 0
weight = get_base_value(sum)
elsif sum = cond.at_css('setOutcomeValue[identifier=D2L_CORRECT] sum baseValue[baseType]')
weight = get_base_value(sum)
elsif base = cond.at_css('setOutcomeValue[identifier=SCORE] > baseValue[baseType]')
weight = get_base_value(base)
elsif base = cond.at_css('setOutcomeValue[identifier^=SCORE] baseValue[baseType]')
weight = get_base_value(base)
elsif base = cond.at_css('setOutcomeValue[identifier$=SCORE] baseValue[baseType]')
weight = get_base_value(base) weight = get_base_value(base)
end end

View File

@ -62,7 +62,7 @@ module Qti
# the python tool "fixes" IDs that aren't quite legal QTI (e.g., "1a" becomes "RESPONSE_1a") # the python tool "fixes" IDs that aren't quite legal QTI (e.g., "1a" becomes "RESPONSE_1a")
# but does not update the question text, breaking fill-in-multiple-blanks questions. # but does not update the question text, breaking fill-in-multiple-blanks questions.
# fortunately it records what it does in an XML comment at the top of the doc, so we can undo it. # fortunately it records what it does in an XML comment at the top of the doc, so we can undo it.
if comment = @doc.children.find { |el| el.class == Nokogiri::XML::Comment } if (comment = @doc.children.find { |el| el.class == Nokogiri::XML::Comment })
regex = /Warning: replacing bad NMTOKEN "([^"]+)" with "([^"]+)"/ regex = /Warning: replacing bad NMTOKEN "([^"]+)" with "([^"]+)"/
match_data = regex.match(comment.text) match_data = regex.match(comment.text)
while match_data while match_data
@ -77,18 +77,18 @@ module Qti
text = get_node_val(match, 'baseValue[baseType=string]') text = get_node_val(match, 'baseValue[baseType=string]')
text ||= get_node_val(match, 'baseValue[baseType=identifier]') text ||= get_node_val(match, 'baseValue[baseType=identifier]')
existing = false existing = false
if @question[:question_type] != 'fill_in_multiple_blanks_question' and answer = @question[:answers].find { |a| a[:text] == text } if @question[:question_type] != 'fill_in_multiple_blanks_question' &&
(answer = @question[:answers].find { |a| a[:text] == text })
existing = true existing = true
else else
answer = {} answer = {}
end end
answer[:text] ||= text answer[:text] ||= text
unless answer[:feedback_id] if !answer[:feedback_id] && (f_id = get_feedback_id(cond))
if f_id = get_feedback_id(cond) answer[:feedback_id] = f_id
answer[:feedback_id] = f_id
end
end end
if @question[:question_type] == 'fill_in_multiple_blanks_question' and id = get_node_att(match, 'variable', 'identifier') if @question[:question_type] == 'fill_in_multiple_blanks_question' &&
(id = get_node_att(match, 'variable', 'identifier'))
id = id.strip id = id.strip
answer[:blank_id] = fib_map[id] || id answer[:blank_id] = fib_map[id] || id
# strip illegal characters from blank ids # strip illegal characters from blank ids

View File

@ -81,7 +81,7 @@ module Qti
def process_canvas def process_canvas
answer_hash = {} answer_hash = {}
@doc.css('choiceInteraction').each do |ci| @doc.css('choiceInteraction').each do |ci|
if blank_id = ci['responseIdentifier'] if (blank_id = ci['responseIdentifier'])
blank_id.gsub!(/^response_/, '') blank_id.gsub!(/^response_/, '')
end end
ci.search('simpleChoice').each do |choice| ci.search('simpleChoice').each do |choice|
@ -100,7 +100,7 @@ module Qti
@doc.css('responseProcessing responseCondition responseIf,responseElseIf').each do |if_node| @doc.css('responseProcessing responseCondition responseIf,responseElseIf').each do |if_node|
if if_node.at_css('setOutcomeValue[identifier=SCORE] sum') if if_node.at_css('setOutcomeValue[identifier=SCORE] sum')
id = if_node.at_css('match baseValue[baseType=identifier]').text id = if_node.at_css('match baseValue[baseType=identifier]').text
if answer = answer_hash[id] if (answer = answer_hash[id])
answer[:weight] = AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT answer[:weight] = AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT
end end
end end
@ -118,7 +118,7 @@ module Qti
@doc.css('responseDeclaration').each do |res_node| @doc.css('responseDeclaration').each do |res_node|
res_id = res_node['identifier'] res_id = res_node['identifier']
res_node.css('correctResponse value').each do |correct_id| res_node.css('correctResponse value').each do |correct_id|
if answer = (answer_hash[res_id] && answer_hash[res_id][correct_id.text]) if (answer = (answer_hash[res_id] && answer_hash[res_id][correct_id.text]))
answer[:weight] = AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT answer[:weight] = AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT
end end
end end
@ -151,7 +151,7 @@ module Qti
def process_d2l def process_d2l
@question[:question_text] = '' @question[:question_text] = ''
if body = @doc.at_css('itemBody') if (body = @doc.at_css('itemBody'))
body.children.each do |node| body.children.each do |node|
next if node.name == 'text' next if node.name == 'text'
@ -167,7 +167,7 @@ module Qti
end end
@doc.css('responseCondition stringMatch').each do |match| @doc.css('responseCondition stringMatch').each do |match|
if blank_id = get_node_att(match, 'variable', 'identifier') if (blank_id = get_node_att(match, 'variable', 'identifier'))
text = get_node_val(match, 'baseValue') text = get_node_val(match, 'baseValue')
answer = { :id => unique_local_id, :weight => AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT } answer = { :id => unique_local_id, :weight => AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT }
answer[:migration_id] = blank_id answer[:migration_id] = blank_id
@ -180,7 +180,7 @@ module Qti
def process_respondus def process_respondus
@doc.css('responseCondition stringMatch baseValue[baseType=string]').each do |val_node| @doc.css('responseCondition stringMatch baseValue[baseType=string]').each do |val_node|
if blank_id = val_node['identifier'] if (blank_id = val_node['identifier'])
blank_id = blank_id.sub(%r{^RESPONSE_-([^-]*)-}, '\1') blank_id = blank_id.sub(%r{^RESPONSE_-([^-]*)-}, '\1')
@question[:answers] << { @question[:answers] << {
:weight => AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT, :weight => AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT,

View File

@ -54,7 +54,7 @@ module Qti
# So check for the file starting with the full relative path, going down to just the file name # So check for the file starting with the full relative path, going down to just the file name
paths = val.split("/") paths = val.split("/")
paths.length.times do |i| paths.length.times do |i|
if mig_id = find_best_path_match(paths[i..-1].join('/')) if (mig_id = find_best_path_match(paths[i..-1].join('/')))
subnode[attr] = "#{CC::CCHelper::OBJECT_TOKEN}/attachments/#{mig_id}" subnode[attr] = "#{CC::CCHelper::OBJECT_TOKEN}/attachments/#{mig_id}"
break break
end end
@ -62,7 +62,7 @@ module Qti
else else
val.gsub!(/\$[A-Z_]*\$/, '') # remove any path tokens like $TOKEN_EH$ val.gsub!(/\$[A-Z_]*\$/, '') # remove any path tokens like $TOKEN_EH$
# try to find the file by exact path match. If not found, try to find best match # try to find the file by exact path match. If not found, try to find best match
if mig_id = find_best_path_match(val) if (mig_id = find_best_path_match(val))
subnode[attr] = "#{CC::CCHelper::OBJECT_TOKEN}/attachments/#{mig_id}" subnode[attr] = "#{CC::CCHelper::OBJECT_TOKEN}/attachments/#{mig_id}"
end end
end end
@ -140,7 +140,7 @@ module Qti
# returns a tuple of [text, html] # returns a tuple of [text, html]
# html is null if it's not an html blob # html is null if it's not an html blob
def detect_html(node) def detect_html(node)
if text_node = node.at_css('div.text') if (text_node = node.at_css('div.text'))
return [text_node.text.strip, nil] return [text_node.text.strip, nil]
end end

View File

@ -37,17 +37,17 @@ module Qti
def get_answer_values def get_answer_values
answer = { :weight => 100, :comments => "", :id => unique_local_id } answer = { :weight => 100, :comments => "", :id => unique_local_id }
if gte = @doc.at_css('responseCondition gte baseValue') if (gte = @doc.at_css('responseCondition gte baseValue'))
answer[:start] = gte.text.to_f answer[:start] = gte.text.to_f
end end
if lte = @doc.at_css('responseCondition lte baseValue') if (lte = @doc.at_css('responseCondition lte baseValue'))
answer[:end] = lte.text.to_f answer[:end] = lte.text.to_f
end end
if (answer[:start] && answer[:end]) if (answer[:start] && answer[:end])
answer[:numerical_answer_type] = "range_answer" answer[:numerical_answer_type] = "range_answer"
@question[:answers] << answer @question[:answers] << answer
elsif equal = @doc.at_css('responseCondition equal baseValue') elsif (equal = @doc.at_css('responseCondition equal baseValue'))
answer[:exact] = equal.text.to_f answer[:exact] = equal.text.to_f
answer[:numerical_answer_type] = "exact_answer" answer[:numerical_answer_type] = "exact_answer"
@question[:answers] << answer @question[:answers] << answer
@ -61,7 +61,7 @@ module Qti
answer[:id] = get_or_generate_answer_id(bv && bv['identifier']) answer[:id] = get_or_generate_answer_id(bv && bv['identifier'])
answer[:feedback_id] = get_feedback_id(r_if) answer[:feedback_id] = get_feedback_id(r_if)
if or_node = r_if.at_css('or') if (or_node = r_if.at_css('or'))
# exact answer # exact answer
exact_node = or_node.at_css('stringMatch baseValue') exact_node = or_node.at_css('stringMatch baseValue')
next unless exact_node next unless exact_node
@ -91,7 +91,7 @@ module Qti
unless is_precision unless is_precision
answer[:numerical_answer_type] = 'exact_answer' answer[:numerical_answer_type] = 'exact_answer'
answer[:exact] = exact.to_f answer[:exact] = exact.to_f
if upper = or_node.at_css('and customOperator[class=varlte] baseValue') if (upper = or_node.at_css('and customOperator[class=varlte] baseValue'))
# do margin computation with BigDecimal to avoid rounding errors # do margin computation with BigDecimal to avoid rounding errors
# (this is also used when _scoring_ numeric range questions) # (this is also used when _scoring_ numeric range questions)
margin = BigDecimal(upper.text) - BigDecimal(exact) rescue "0.0" margin = BigDecimal(upper.text) - BigDecimal(exact) rescue "0.0"
@ -99,13 +99,13 @@ module Qti
end end
end end
@question[:answers] << answer @question[:answers] << answer
elsif and_node = r_if.at_css('and') elsif (and_node = r_if.at_css('and'))
# range answer # range answer
answer[:numerical_answer_type] = 'range_answer' answer[:numerical_answer_type] = 'range_answer'
if lower = and_node.at_css('customOperator[class=vargte] baseValue') if (lower = and_node.at_css('customOperator[class=vargte] baseValue'))
answer[:start] = lower.text.to_f rescue 0.0 answer[:start] = lower.text.to_f rescue 0.0
end end
if upper = and_node.at_css('customOperator[class=varlte] baseValue') if (upper = and_node.at_css('customOperator[class=varlte] baseValue'))
answer[:end] = upper.text.to_f rescue 0.0 answer[:end] = upper.text.to_f rescue 0.0
end end
if upper || lower if upper || lower

View File

@ -28,7 +28,7 @@ module Qti
def parse_question_data def parse_question_data
match_map = {} match_map = {}
get_all_matches(match_map) get_all_matches(match_map)
if node = @doc.at_css('correctResponse') if (node = @doc.at_css('correctResponse'))
get_correct_responses(match_map) get_correct_responses(match_map)
else else
get_all_answers(match_map) get_all_answers(match_map)
@ -38,7 +38,7 @@ module Qti
end end
def get_all_matches(match_map) def get_all_matches(match_map)
if matches = @doc.at_css('orderInteraction') if (matches = @doc.at_css('orderInteraction'))
matches.css('simpleChoice').each do |sc| matches.css('simpleChoice').each do |sc|
match = {} match = {}
@question[:matches] << match @question[:matches] << match
@ -57,7 +57,7 @@ module Qti
answer[:id] = unique_local_id answer[:id] = unique_local_id
answer[:comments] = "" answer[:comments] = ""
if option = a.at_css('baseValue') if (option = a.at_css('baseValue'))
answer[:match_id] = match_map[option.text.strip] answer[:match_id] = match_map[option.text.strip]
end end
end end
@ -72,7 +72,7 @@ module Qti
answer[:comments] = "" answer[:comments] = ""
match_id = answ.text.strip match_id = answ.text.strip
if m = match_map[match_id] if (m = match_map[match_id])
answer[:match_id] = m answer[:match_id] = m
end end
end end

View File

@ -75,7 +75,7 @@ module Qti
protected protected
def apply_if_set(assessment, key, setting_name, &block) def apply_if_set(assessment, key, setting_name, &block)
if setting = read_setting(setting_name) if (setting = read_setting(setting_name))
assessment[key] = block ? block.call(setting) : setting assessment[key] = block ? block.call(setting) : setting
end end
end end

View File

@ -60,16 +60,16 @@ if Qti.migration_executable
expect(manifest_node.at_css("instructureMetadata")).to eq manifest_node expect(manifest_node.at_css("instructureMetadata")).to eq manifest_node
expect(manifest_node['identifier']).to eq nil expect(manifest_node['identifier']).to eq nil
expect(manifest_node['href']).to eq 'multiple_choice.xml' expect(manifest_node['href']).to eq 'multiple_choice.xml'
if title = manifest_node.at_css('title langstring') if (title = manifest_node.at_css('title langstring'))
expect(title.text).to eq nil expect(title.text).to eq nil
end end
if type = manifest_node.at_css('interactiontype') if (type = manifest_node.at_css('interactiontype'))
expect(type.text.downcase).to eq 'extendedtextinteraction' expect(type.text.downcase).to eq 'extendedtextinteraction'
end end
if type = manifest_node.at_css('instructureMetadata instructureField[name=quiz_type]') if (type = manifest_node.at_css('instructureMetadata instructureField[name=quiz_type]'))
expect(type['value'].downcase).to eq 'calculated' expect(type['value'].downcase).to eq 'calculated'
end end
if type = manifest_node.at_css('instructureField[name=bb8_assessment_type]') if (type = manifest_node.at_css('instructureField[name=bb8_assessment_type]'))
expect(type['value'].downcase).to eq 'calculated' expect(type['value'].downcase).to eq 'calculated'
end end
end end

View File

@ -129,7 +129,7 @@ module RuboCop
mod_name_parts = mod_name.to_a mod_name_parts = mod_name.to_a
result = [mod_name_parts[1]] result = [mod_name_parts[1]]
top_level = false top_level = false
if parent = mod_name_parts[0] if (parent = mod_name_parts[0])
if parent.cbase_type? if parent.cbase_type?
top_level = true top_level = true
elsif parent.const_type? elsif parent.const_type?

View File

@ -28,7 +28,7 @@ module Api::V1::Account
# which should act similarly to the account_json method, but include a parameter 'hash' # which should act similarly to the account_json method, but include a parameter 'hash'
# which will have the current account json (to which the method is expected to change and return) # which will have the current account json (to which the method is expected to change and return)
def self.register_extension(extension) def self.register_extension(extension)
if result = extension.respond_to?(:extend_account_json) if (result = extension.respond_to?(:extend_account_json))
@@extensions << extension @@extensions << extension
end end
result result

View File

@ -285,7 +285,8 @@ module Api::V1::Assignment
rating_hash["long_description"] = c[:long_description] || "" rating_hash["long_description"] = c[:long_description] || ""
rating_hash rating_hash
end end
if row[:learning_outcome_id] && outcome = LearningOutcome.where(id: row[:learning_outcome_id]).first if row[:learning_outcome_id] &&
(outcome = LearningOutcome.where(id: row[:learning_outcome_id]).first)
row_hash["outcome_id"] = outcome.id row_hash["outcome_id"] = outcome.id
row_hash["vendor_guid"] = outcome.vendor_guid row_hash["vendor_guid"] = outcome.vendor_guid
end end
@ -357,7 +358,7 @@ module Api::V1::Assignment
hash['assignment_visibility'] = (opts[:assignment_visibilities] || assignment.students_with_visibility.pluck(:id).uniq).map(&:to_s) hash['assignment_visibility'] = (opts[:assignment_visibilities] || assignment.students_with_visibility.pluck(:id).uniq).map(&:to_s)
end end
if submission = opts[:submission] if (submission = opts[:submission])
should_show_statistics = opts[:include_score_statistics] && assignment.can_view_score_statistics?(user) should_show_statistics = opts[:include_score_statistics] && assignment.can_view_score_statistics?(user)
if submission.is_a?(Array) if submission.is_a?(Array)

View File

@ -204,7 +204,7 @@ module Api::V1::AssignmentOverride
if data[field].blank? if data[field].blank?
# override value of nil/'' is meaningful # override value of nil/'' is meaningful
override_data[field] = nil override_data[field] = nil
elsif value = Time.zone.parse(data[field].to_s) elsif (value = Time.zone.parse(data[field].to_s))
override_data[field] = value override_data[field] = value
else else
errors << "invalid #{field} #{data[field].inspect}" errors << "invalid #{field} #{data[field].inspect}"

View File

@ -133,7 +133,7 @@ module Api::V1::CalendarEvent
else else
hash['reserve_url'] = api_v1_calendar_event_reserve_url(event, '{{ id }}') hash['reserve_url'] = api_v1_calendar_event_reserve_url(event, '{{ id }}')
end end
if participant_limit = event.participants_per_appointment if (participant_limit = event.participants_per_appointment)
hash["available_slots"] = [participant_limit - event.child_events.size, 0].max hash["available_slots"] = [participant_limit - event.child_events.size, 0].max
hash["participants_per_appointment"] = participant_limit hash["participants_per_appointment"] = participant_limit
end end

View File

@ -51,7 +51,8 @@ module Api::V1::ContentMigration
end end
if migration.for_course_copy? if migration.for_course_copy?
if source = migration.source_course || (migration.migration_settings[:source_course_id] && Course.find(migration.migration_settings[:source_course_id])) if (source = migration.source_course ||
(migration.migration_settings[:source_course_id] && Course.find(migration.migration_settings[:source_course_id])))
json[:settings] = {} json[:settings] = {}
json[:settings][:source_course_id] = source.id json[:settings][:source_course_id] = source.id
json[:settings][:source_course_name] = source.name json[:settings][:source_course_name] = source.name
@ -62,7 +63,7 @@ module Api::V1::ContentMigration
if migration.job_progress if migration.job_progress
json['progress_url'] = polymorphic_url([:api_v1, migration.job_progress]) json['progress_url'] = polymorphic_url([:api_v1, migration.job_progress])
end end
if plugin = Canvas::Plugin.find(migration.migration_type) if (plugin = Canvas::Plugin.find(migration.migration_type))
if plugin.meta[:display_name] && plugin.meta[:display_name].respond_to?(:call) if plugin.meta[:display_name] && plugin.meta[:display_name].respond_to?(:call)
json['migration_type_title'] = plugin.meta[:display_name].call json['migration_type_title'] = plugin.meta[:display_name].call
elsif plugin.meta[:name] && plugin.meta[:name].respond_to?(:call) elsif plugin.meta[:name] && plugin.meta[:name].respond_to?(:call)

View File

@ -142,7 +142,7 @@ module Api::V1::ContextModule
end end
# add completion requirements # add completion requirements
if criterion = context_module.completion_requirements && context_module.completion_requirements.detect { |r| r[:id] == content_tag.id } if (criterion = context_module.completion_requirements&.detect { |r| r[:id] == content_tag.id })
ch = { 'type' => criterion[:type] } ch = { 'type' => criterion[:type] }
ch['min_score'] = criterion[:min_score] if criterion[:type] == 'min_score' ch['min_score'] = criterion[:min_score] if criterion[:type] == 'min_score'
ch['completed'] = !!(progression.requirements_met.present? && progression.requirements_met.detect { |r| r[:type] == criterion[:type] && r[:id] == content_tag.id }) if progression ch['completed'] = !!(progression.requirements_met.present? && progression.requirements_met.detect { |r| r[:type] == criterion[:type] && r[:id] == content_tag.id }) if progression
@ -175,7 +175,7 @@ module Api::V1::ContextModule
attrs = [:usage_rights, :locked, :hidden, :lock_explanation, :display_name, :due_at, :unlock_at, :lock_at, :points_possible] attrs = [:usage_rights, :locked, :hidden, :lock_explanation, :display_name, :due_at, :unlock_at, :lock_at, :points_possible]
attrs.each do |attr| attrs.each do |attr|
if item.respond_to?(attr) && val = item.try(attr) if (val = item.try(attr))
details[attr] = val details[attr] = val
end end
end end

View File

@ -218,7 +218,7 @@ module Api::V1::Course
teacher_counts = Enrollment.from("(#{scope.to_sql}) AS t").group("t.course_id").count teacher_counts = Enrollment.from("(#{scope.to_sql}) AS t").group("t.course_id").count
to_preload = [] to_preload = []
courses.each do |course| courses.each do |course|
next unless count = teacher_counts[course.id] next unless (count = teacher_counts[course.id])
if count > threshold if count > threshold
course.teacher_count = count course.teacher_count = count

View File

@ -64,7 +64,7 @@ module Api::V1
@hash['workflow_state'] = @course.api_state @hash['workflow_state'] = @course.api_state
@hash['course_format'] = @course.course_format if @course.course_format.present? @hash['course_format'] = @course.course_format if @course.course_format.present?
@hash['restrict_enrollments_to_course_dates'] = !!@course.restrict_enrollments_to_course_dates @hash['restrict_enrollments_to_course_dates'] = !!@course.restrict_enrollments_to_course_dates
if visibility = @course.overridden_course_visibility if (visibility = @course.overridden_course_visibility)
@hash['overridden_course_visibility'] = visibility @hash['overridden_course_visibility'] = visibility
end end
if @includes.include?(:current_grading_period_scores) if @includes.include?(:current_grading_period_scores)

View File

@ -113,7 +113,7 @@ module Api::V1::DiscussionTopics
json.merge!(serialize_additional_topic_fields(topic, context, user, opts)) json.merge!(serialize_additional_topic_fields(topic, context, user, opts))
if hold = topic.subscription_hold(user, @context_enrollment, session) if (hold = topic.subscription_hold(user, @context_enrollment, session))
json[:subscription_hold] = hold json[:subscription_hold] = hold
end end

View File

@ -61,7 +61,7 @@ module Api::V1::FeatureFlag
private private
def add_localized_attr(hash, feature, attr_name) def add_localized_attr(hash, feature, attr_name)
if attr = feature.instance_variable_get("@#{attr_name}") if (attr = feature.instance_variable_get("@#{attr_name}"))
hash[attr_name] = attr.is_a?(Proc) ? attr.call : attr.to_s hash[attr_name] = attr.is_a?(Proc) ? attr.call : attr.to_s
end end
end end

View File

@ -149,11 +149,11 @@ module Api::V1
collection = collection.where("graded_at IS NOT NULL") collection = collection.where("graded_at IS NOT NULL")
end end
if assignment_id = options[:assignment_id] if (assignment_id = options[:assignment_id])
collection = collection.where(assignment_id: assignment_id) collection = collection.where(assignment_id: assignment_id)
end end
if grader_id = options[:grader_id] if (grader_id = options[:grader_id])
if grader_id.to_s == '0' if grader_id.to_s == '0'
# yes, this is crazy. autograded submissions have the grader_id of (quiz_id x -1) # yes, this is crazy. autograded submissions have the grader_id of (quiz_id x -1)
collection = collection.where("submissions.grader_id<=0") collection = collection.where("submissions.grader_id<=0")

View File

@ -366,7 +366,7 @@ module AssignmentOverrideApplicator
applicable_overrides = overrides.select(&:due_at_overridden) applicable_overrides = overrides.select(&:due_at_overridden)
if applicable_overrides.empty? if applicable_overrides.empty?
assignment_or_quiz assignment_or_quiz
elsif override = applicable_overrides.detect { |o| o.due_at.nil? } elsif (override = applicable_overrides.detect { |o| o.due_at.nil? })
override override
else else
applicable_overrides.sort_by(&:due_at).last applicable_overrides.sort_by(&:due_at).last

View File

@ -281,7 +281,7 @@ module BasicLTI
self.description = error_message self.description = error_message
elsif assignment.grading_type != "pass_fail" && (assignment.points_possible.nil?) elsif assignment.grading_type != "pass_fail" && (assignment.points_possible.nil?)
unless submission = existing_submission unless (submission = existing_submission)
submission = Submission.create!(submission_hash.merge(:user => user, submission = Submission.create!(submission_hash.merge(:user => user,
:assignment => assignment)) :assignment => assignment))
end end
@ -410,7 +410,7 @@ module BasicLTI
def to_xml def to_xml
xml = LtiResponse::Legacy.envelope.dup xml = LtiResponse::Legacy.envelope.dup
xml.at_css('message_response > statusinfo > codemajor').content = code_major.capitalize xml.at_css('message_response > statusinfo > codemajor').content = code_major.capitalize
if score = submission_score if (score = submission_score)
xml.at_css('message_response > result > sourcedid').content = sourcedid xml.at_css('message_response > result > sourcedid').content = sourcedid
xml.at_css('message_response > result > resultscore > textstring').content = score xml.at_css('message_response > result > resultscore > textstring').content = score
else else

View File

@ -119,7 +119,7 @@ class BrandConfigRegenerator
total += five_percent total += five_percent
@progress.calculate_completion!(five_percent, total) @progress.calculate_completion!(five_percent, total)
# take things off the queue from front-to-back # take things off the queue from front-to-back
while thing = things_left_to_process.shift while (thing = things_left_to_process.shift)
# if for some reason this one isn't ready (it _should_ be by default, # if for some reason this one isn't ready (it _should_ be by default,
# because we get higher tiers first) put it back on the queue to try # because we get higher tiers first) put it back on the queue to try
# again later # again later

View File

@ -39,7 +39,7 @@ module Canvas::Migration::ExternalContent
self.registered_services.each do |key, service| self.registered_services.each do |key, service|
if service.applies_to_course?(course) if service.applies_to_course?(course)
begin begin
if export = service.begin_export(course, opts) if (export = service.begin_export(course, opts))
pending_exports[key] = export pending_exports[key] = export
end end
rescue => e rescue => e
@ -125,7 +125,7 @@ module Canvas::Migration::ExternalContent
service = import_service_for(key) service = import_service_for(key)
if service if service
begin begin
if import = service.send_imported_content(migration.context, migration, content) if (import = service.send_imported_content(migration.context, migration, content))
pending_imports[key] = import pending_imports[key] = import
end end
rescue => e rescue => e

View File

@ -95,7 +95,7 @@ module Canvas::Migration::Helpers
@migration.context.root_account.feature_enabled?(:selectable_outcomes_in_course_copy) @migration.context.root_account.feature_enabled?(:selectable_outcomes_in_course_copy)
content_list = [] content_list = []
if type if type
if match_data = type.match(/submodules_(.*)/) if (match_data = type.match(/submodules_(.*)/))
(submodule_data(course_data['context_modules'], match_data[1]) || []).each do |item| (submodule_data(course_data['context_modules'], match_data[1]) || []).each do |item|
content_list << item_hash('context_modules', item) content_list << item_hash('context_modules', item)
end end
@ -220,9 +220,11 @@ module Canvas::Migration::Helpers
hash[:title] = item['file_name'] hash[:title] = item['file_name']
when 'assessment_question_banks' when 'assessment_question_banks'
if hash[:title].blank? && @migration && @migration.context.respond_to?(:assessment_question_banks) if hash[:title].blank? && @migration && @migration.context.respond_to?(:assessment_question_banks)
if hash[:migration_id] && bank = @migration.context.assessment_question_banks.where(migration_id: hash[:migration_id]).first if hash[:migration_id] &&
(bank = @migration.context.assessment_question_banks.where(migration_id: hash[:migration_id]).first)
hash[:title] = bank.title hash[:title] = bank.title
elsif @migration.question_bank_id && default_bank = @migration.context.assessment_question_banks.where(id: @migration.question_bank_id).first elsif @migration.question_bank_id &&
(default_bank = @migration.context.assessment_question_banks.where(id: @migration.question_bank_id).first)
hash[:title] = default_bank.title hash[:title] = default_bank.title
end end
hash[:title] ||= @migration.question_bank_name || AssessmentQuestionBank.default_imported_title hash[:title] ||= @migration.question_bank_name || AssessmentQuestionBank.default_imported_title
@ -241,14 +243,15 @@ module Canvas::Migration::Helpers
def add_linked_resource(type, item, hash) def add_linked_resource(type, item, hash)
if type == 'assignments' if type == 'assignments'
if mig_id = item['quiz_migration_id'] if (mig_id = item['quiz_migration_id'])
hash[:linked_resource] = { :type => 'quizzes', :migration_id => mig_id } hash[:linked_resource] = { :type => 'quizzes', :migration_id => mig_id }
elsif mig_id = item['topic_migration_id'] elsif (mig_id = item['topic_migration_id'])
hash[:linked_resource] = { :type => 'discussion_topics', :migration_id => mig_id } hash[:linked_resource] = { :type => 'discussion_topics', :migration_id => mig_id }
elsif mig_id = item['page_migration_id'] elsif (mig_id = item['page_migration_id'])
hash[:linked_resource] = { :type => 'wiki_pages', :migration_id => mig_id } hash[:linked_resource] = { :type => 'wiki_pages', :migration_id => mig_id }
end end
elsif ['discussion_topics', 'quizzes', 'wiki_pages'].include?(type) && mig_id = item['assignment_migration_id'] elsif ['discussion_topics', 'quizzes', 'wiki_pages'].include?(type) &&
(mig_id = item['assignment_migration_id'])
hash[:linked_resource] = { :type => 'assignments', :migration_id => mig_id } hash[:linked_resource] = { :type => 'assignments', :migration_id => mig_id }
end end
hash hash
@ -449,7 +452,7 @@ module Canvas::Migration::Helpers
end end
def submodule_data(modules, parent_mig_id) def submodule_data(modules, parent_mig_id)
if mod = modules.detect { |m| m['migration_id'] == parent_mig_id } if (mod = modules.detect { |m| m['migration_id'] == parent_mig_id })
mod['submodules'] mod['submodules']
else else
modules.each do |mod| modules.each do |mod|

View File

@ -130,7 +130,7 @@ module Canvas::Migration
r_node.css('dependency').each do |d_node| r_node.css('dependency').each do |d_node|
resource[:dependencies] << d_node[:identifierref] resource[:dependencies] << d_node[:identifierref]
end end
if variant = r_node.at_css('variant') if (variant = r_node.at_css('variant'))
resource[:preferred_resource_id] = variant['identifierref'] resource[:preferred_resource_id] = variant['identifierref']
end end
@resources[id] = resource @resources[id] = resource
@ -158,20 +158,20 @@ module Canvas::Migration
doc = open_rel_path(resource[:href]) doc = open_rel_path(resource[:href])
if !doc && resource[:files] if !doc && resource[:files]
resource[:files].each do |file| resource[:files].each do |file|
break if doc = open_rel_path(file[:href]) break if (doc = open_rel_path(file[:href]))
end end
end end
if !doc && node = @resource_nodes_for_flat_manifest[resource[:migration_id]] if !doc && (node = @resource_nodes_for_flat_manifest[resource[:migration_id]])
# check for in-line node # check for in-line node
if node_name doc = if node_name
doc = node.children.find { |c| c.name == node_name } node.children.find { |c| c.name == node_name }
else else
doc = node node
end end
end end
doc.remove_namespaces! if doc && doc.respond_to?('remove_namespaces!') doc.remove_namespaces! if doc.respond_to?('remove_namespaces!')
doc doc
end end
end end

View File

@ -71,7 +71,7 @@ module Canvas::Migration
def unique_quiz_dir def unique_quiz_dir
if content_migration if content_migration
if a = content_migration.attachment if (a = content_migration.attachment)
key = "#{a.filename.gsub(/\..*/, '')}_#{content_migration.id}" key = "#{a.filename.gsub(/\..*/, '')}_#{content_migration.id}"
else else
key = content_migration.id.to_s key = content_migration.id.to_s
@ -186,7 +186,7 @@ module Canvas::Migration
assessments.each do |a| assessments.each do |a|
if a[:migration_id].present? && should_prepend?(:assessments, a[:migration_id], existing_ids) if a[:migration_id].present? && should_prepend?(:assessments, a[:migration_id], existing_ids)
a[:migration_id] = prepend_id(a[:migration_id], prepend_value) a[:migration_id] = prepend_id(a[:migration_id], prepend_value)
if h = a[:assignment] if (h = a[:assignment])
h[:migration_id] = prepend_id(h[:migration_id], prepend_value) h[:migration_id] = prepend_id(h[:migration_id], prepend_value)
end end
end end
@ -274,7 +274,7 @@ module Canvas::Migration
@overview[:start_timestamp] = nil @overview[:start_timestamp] = nil
@overview[:end_timestamp] = nil @overview[:end_timestamp] = nil
dates = [] dates = []
if @overview[:course] = @course[:course] if (@overview[:course] = @course[:course])
@overview[:start_timestamp] = @course[:course][:start_timestamp] || @course[:course][:start_at] @overview[:start_timestamp] = @course[:course][:start_timestamp] || @course[:course][:start_at]
@overview[:end_timestamp] = @course[:course][:end_timestamp] || @course[:course][:conclude_at] @overview[:end_timestamp] = @course[:course][:end_timestamp] || @course[:course][:conclude_at]
end end
@ -398,7 +398,7 @@ module Canvas::Migration
topic[:title] = t[:title] topic[:title] = t[:title]
topic[:migration_id] = t[:migration_id] topic[:migration_id] = t[:migration_id]
topic[:error_message] = t[:error_message] if t[:error_message] topic[:error_message] = t[:error_message] if t[:error_message]
if t[:assignment] && a_mig_id = t[:assignment][:migration_id] if t[:assignment] && (a_mig_id = t[:assignment][:migration_id])
topic[:assignment_migration_id] = a_mig_id topic[:assignment_migration_id] = a_mig_id
ensure_linked_assignment(t[:assignment], topic_migration_id: t[:migration_id]) ensure_linked_assignment(t[:assignment], topic_migration_id: t[:migration_id])
end end
@ -431,7 +431,7 @@ module Canvas::Migration
@overview[:wikis] << wiki @overview[:wikis] << wiki
wiki[:migration_id] = w[:migration_id] wiki[:migration_id] = w[:migration_id]
wiki[:title] = w[:title] wiki[:title] = w[:title]
if w[:assignment] && a_mig_id = w[:assignment][:migration_id] if w[:assignment] && (a_mig_id = w[:assignment][:migration_id])
wiki[:assignment_migration_id] = a_mig_id wiki[:assignment_migration_id] = a_mig_id
ensure_linked_assignment(w[:assignment], page_migration_id: w[:migration_id]) ensure_linked_assignment(w[:assignment], page_migration_id: w[:migration_id])
end end

View File

@ -116,7 +116,7 @@ module Canvas::Migration
end end
def find_converter def find_converter
if plugin = Canvas::Plugin.all_for_tag(:export_system).find { |p| p.settings[:provides] && p.settings[:provides][@type] } if (plugin = Canvas::Plugin.all_for_tag(:export_system).find { |p| p.settings[:provides] && p.settings[:provides][@type] })
return plugin.settings[:provides][@type] return plugin.settings[:provides][@type]
end end

View File

@ -29,7 +29,7 @@ module Canvas::Migration
end end
def get_node_att(node, selector, attribute, default = nil) def get_node_att(node, selector, attribute, default = nil)
if node = node.at_css(selector) if (node = node.at_css(selector))
return node[attribute] return node[attribute]
end end
@ -44,7 +44,7 @@ module Canvas::Migration
# descendants of the current node, so you have to iterate # descendants of the current node, so you have to iterate
# over the children and see if it's there. # over the children and see if it's there.
def get_val_if_child(node, name) def get_val_if_child(node, name)
if child = node.children.find { |c| c.name == name } if (child = node.children.find { |c| c.name == name })
return child.text return child.text
end end

View File

@ -64,7 +64,7 @@ module Canvas::Plugins::TicketingSystem
end end
def sub_account_tag(asset_manager = ::Context, expected_type = Course) def sub_account_tag(asset_manager = ::Context, expected_type = Course)
if context_string = self.data['context_asset_string'] if (context_string = self.data['context_asset_string'])
context = asset_manager.find_by_asset_string(context_string) context = asset_manager.find_by_asset_string(context_string)
if context.is_a? expected_type if context.is_a? expected_type
"subaccount_#{context.account_id}" "subaccount_#{context.account_id}"

View File

@ -29,7 +29,7 @@ module Canvas::Plugins::Validators::GoogleDriveValidator
:token_uri => '', :token_uri => '',
:client_secret_json => '' :client_secret_json => ''
} }
elsif res = check_json(settings) elsif (res = check_json(settings))
plugin_setting.errors.add(:base, res) plugin_setting.errors.add(:base, res)
false false
else else

View File

@ -142,7 +142,7 @@ module CC
end end
node.submission_formats do |fmt| node.submission_formats do |fmt|
assignment.submission_types.split(',').each do |st| assignment.submission_types.split(',').each do |st|
if cc_type = SUBMISSION_TYPE_MAP[st] if (cc_type = SUBMISSION_TYPE_MAP[st])
fmt.format(:type => cc_type) fmt.format(:type => cc_type)
end end
end end

View File

@ -139,7 +139,7 @@ module CC
if tab['id'].is_a?(String) if tab['id'].is_a?(String)
# it's an external tool, so translate the id to a migration_id # it's an external tool, so translate the id to a migration_id
tool_id = tab['id'].sub('context_external_tool_', '') tool_id = tab['id'].sub('context_external_tool_', '')
if tool = ContextExternalTool.find_for(tool_id, @course, :course_navigation, false) if (tool = ContextExternalTool.find_for(tool_id, @course, :course_navigation, false))
tab['id'] = "context_external_tool_#{create_key(tool)}" tab['id'] = "context_external_tool_#{create_key(tool)}"
end end
end end
@ -156,7 +156,7 @@ module CC
if @course.image_url.present? if @course.image_url.present?
atts << :image_url atts << :image_url
elsif @course.image_id.present? elsif @course.image_id.present?
if image_att = @course.attachments.active.where(id: @course.image_id).first if (image_att = @course.attachments.active.where(id: @course.image_id).first)
c.image_identifier_ref(create_key(image_att)) c.image_identifier_ref(create_key(image_att))
end end
end end

View File

@ -143,7 +143,7 @@ module CC
def get_html_title_and_body_and_meta_fields(doc) def get_html_title_and_body_and_meta_fields(doc)
meta_fields = {} meta_fields = {}
doc.css('html head meta').each do |meta_node| doc.css('html head meta').each do |meta_node|
if key = meta_node['name'] if (key = meta_node['name'])
meta_fields[key] = meta_node['content'] meta_fields[key] = meta_node['content']
end end
end end
@ -232,7 +232,7 @@ module CC
end end
@rewriter.set_handler('files') do |match| @rewriter.set_handler('files') do |match|
if match.obj_id.nil? if match.obj_id.nil?
if match_data = match.url.match(%r{/files/folder/(.*)}) if (match_data = match.url.match(%r{/files/folder/(.*)}))
# this might not be the best idea but let's keep going and see what happens # this might not be the best idea but let's keep going and see what happens
"#{COURSE_TOKEN}/files/folder/#{match_data[1]}" "#{COURSE_TOKEN}/files/folder/#{match_data[1]}"
elsif match.prefix.present? elsif match.prefix.present?
@ -348,7 +348,7 @@ module CC
media_id = anchor['id'].gsub(/^media_comment_/, '') media_id = anchor['id'].gsub(/^media_comment_/, '')
obj = MediaObject.active.by_media_id(media_id).first obj = MediaObject.active.by_media_id(media_id).first
if obj && migration_id = @key_generator.create_key(obj) if obj && (migration_id = @key_generator.create_key(obj))
@used_media_objects << obj @used_media_objects << obj
info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor) info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor)
@media_object_infos[obj.id] = info @media_object_infos[obj.id] = info
@ -360,7 +360,7 @@ module CC
doc.css('iframe[data-media-id]').each do |iframe| doc.css('iframe[data-media-id]').each do |iframe|
media_id = iframe['data-media-id'] media_id = iframe['data-media-id']
obj = MediaObject.active.by_media_id(media_id).take obj = MediaObject.active.by_media_id(media_id).take
if obj && migration_id = @key_generator.create_key(obj) if obj && (migration_id = @key_generator.create_key(obj))
@used_media_objects << obj @used_media_objects << obj
info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor) info = CCHelper.media_object_info(obj, course: @course, flavor: media_object_flavor)
@media_object_infos[obj.id] = info @media_object_infos[obj.id] = info

View File

@ -63,7 +63,7 @@ module CC::Exporter::Epub::Converters
topic[:identifier] = get_node_val(meta_doc, 'topic_id') topic[:identifier] = get_node_val(meta_doc, 'topic_id')
topic[:href] = "topics.xhtml##{topic[:identifier]}" topic[:href] = "topics.xhtml##{topic[:identifier]}"
if asmnt_node = meta_doc.at_css('assignment') if (asmnt_node = meta_doc.at_css('assignment'))
topic[:assignment] = assignment_data(asmnt_node) topic[:assignment] = assignment_data(asmnt_node)
end end
end end

View File

@ -91,7 +91,7 @@ module CC::Importer
tool[:consumer_key] = ext[:custom_fields].delete 'consumer_key' tool[:consumer_key] = ext[:custom_fields].delete 'consumer_key'
tool[:shared_secret] = ext[:custom_fields].delete 'shared_secret' tool[:shared_secret] = ext[:custom_fields].delete 'shared_secret'
tool[:tool_id] = ext[:custom_fields].delete 'tool_id' tool[:tool_id] = ext[:custom_fields].delete 'tool_id'
if tool[:assignment_points_possible] = ext[:custom_fields].delete('outcome') if (tool[:assignment_points_possible] = ext[:custom_fields].delete('outcome'))
tool[:assignment_points_possible] = tool[:assignment_points_possible].to_f tool[:assignment_points_possible] = tool[:assignment_points_possible].to_f
end end
tool[:settings] = ext[:custom_fields] tool[:settings] = ext[:custom_fields]

View File

@ -26,7 +26,7 @@ module CC::Importer::Canvas
assignments = convert_cc_assignments assignments = convert_cc_assignments
@manifest.css('resource[type$=learning-application-resource]').each do |res| @manifest.css('resource[type$=learning-application-resource]').each do |res|
if meta_path = res.at_css('file[href$="assignment_settings.xml"]') if (meta_path = res.at_css('file[href$="assignment_settings.xml"]'))
meta_path = @package_root.item_path meta_path['href'] meta_path = @package_root.item_path meta_path['href']
html_path = @package_root.item_path res.at_css('file[href$="html"]')['href'] html_path = @package_root.item_path res.at_css('file[href$="html"]')['href']

View File

@ -39,7 +39,7 @@ module CC::Importer::Canvas
def convert_all_course_settings def convert_all_course_settings
@course[:course] = convert_course_settings(settings_doc(COURSE_SETTINGS)) @course[:course] = convert_course_settings(settings_doc(COURSE_SETTINGS))
if doc = settings_doc(SYLLABUS, true) if (doc = settings_doc(SYLLABUS, true))
@course[:course][:syllabus_body] = convert_syllabus(doc) @course[:course][:syllabus_body] = convert_syllabus(doc)
end end
@course[:assignment_groups] = convert_assignment_groups(settings_doc(ASSIGNMENT_GROUPS)) @course[:assignment_groups] = convert_assignment_groups(settings_doc(ASSIGNMENT_GROUPS))
@ -87,11 +87,11 @@ module CC::Importer::Canvas
course[date_type] = val course[date_type] = val
end end
['grading_standard_id', 'home_page_announcement_limit'].each do |int_val| ['grading_standard_id', 'home_page_announcement_limit'].each do |int_val|
if val = get_int_val(doc, int_val) if (val = get_int_val(doc, int_val))
course[int_val] = val course[int_val] = val
end end
end end
if nav = get_node_val(doc, 'tab_configuration') if (nav = get_node_val(doc, 'tab_configuration'))
begin begin
nav = JSON.parse(nav) nav = JSON.parse(nav)
# Validate the format a little bit # Validate the format a little bit

View File

@ -25,7 +25,7 @@ module CC::Importer::Canvas
track_map = {} track_map = {}
return track_map unless doc return track_map unless doc
if media_tracks = doc.at_css('media_tracks') if (media_tracks = doc.at_css('media_tracks'))
media_tracks.css('media').each do |media| media_tracks.css('media').each do |media|
file_migration_id = media['identifierref'] file_migration_id = media['identifierref']
tracks = [] tracks = []

View File

@ -30,7 +30,7 @@ module CC::Importer::Canvas
@manifest.css('resource[type$="learning-application-resource"]').each do |res| @manifest.css('resource[type$="learning-application-resource"]').each do |res|
res.css('file').select { |f| f['href'].to_s.end_with?(ASSESSMENT_META) }.each do |file| res.css('file').select { |f| f['href'].to_s.end_with?(ASSESSMENT_META) }.each do |file|
meta_path = file['href'] meta_path = file['href']
if quiz = quiz_map[meta_path] if (quiz = quiz_map[meta_path])
doc = open_file_xml(@package_root.item_path(meta_path)) doc = open_file_xml(@package_root.item_path(meta_path))
get_quiz_meta(doc, quiz) get_quiz_meta(doc, quiz)
end end
@ -74,7 +74,7 @@ module CC::Importer::Canvas
quiz[bool_val] = val unless val.nil? quiz[bool_val] = val unless val.nil?
end end
if asmnt_node = doc.at_css('assignment') if (asmnt_node = doc.at_css('assignment'))
quiz['assignment'] = parse_canvas_assignment_data(asmnt_node) quiz['assignment'] = parse_canvas_assignment_data(asmnt_node)
end end

View File

@ -29,7 +29,7 @@ module CC::Importer::Canvas
cc_path = @package_root.item_path res.at_css('file')['href'] cc_path = @package_root.item_path res.at_css('file')['href']
cc_id = res['identifier'] cc_id = res['identifier']
canvas_id = get_node_att(res, 'dependency', 'identifierref') canvas_id = get_node_att(res, 'dependency', 'identifierref')
if canvas_id && meta_res = @manifest.at_css(%{resource[identifier="#{canvas_id}"]}) if canvas_id && (meta_res = @manifest.at_css(%{resource[identifier="#{canvas_id}"]}))
canvas_path = @package_root.item_path meta_res.at_css('file')['href'] canvas_path = @package_root.item_path meta_res.at_css('file')['href']
meta_node = open_file_xml(canvas_path) meta_node = open_file_xml(canvas_path)
else else
@ -73,7 +73,7 @@ module CC::Importer::Canvas
%w(has_group_category allow_rating only_graders_can_rate sort_by_rating locked).each do |setting| %w(has_group_category allow_rating only_graders_can_rate sort_by_rating locked).each do |setting|
get_bool_val(meta_doc, setting).tap { |val| topic[setting] = val unless val.nil? } get_bool_val(meta_doc, setting).tap { |val| topic[setting] = val unless val.nil? }
end end
if asmnt_node = meta_doc.at_css('assignment') if (asmnt_node = meta_doc.at_css('assignment'))
topic['assignment'] = parse_canvas_assignment_data(asmnt_node) topic['assignment'] = parse_canvas_assignment_data(asmnt_node)
end end
end end

View File

@ -45,7 +45,7 @@ module CC::Importer::Canvas
doc = open_file_xml path doc = open_file_xml path
if folders = doc.at_css('folders') if (folders = doc.at_css('folders'))
@course[:hidden_folders] = [] @course[:hidden_folders] = []
@course[:locked_folders] = [] @course[:locked_folders] = []
folders.css('folder').each do |folder| folders.css('folder').each do |folder|
@ -54,29 +54,29 @@ module CC::Importer::Canvas
end end
end end
if files = doc.at_css('files') if (files = doc.at_css('files'))
files.css('file').each do |file| files.css('file').each do |file|
id = file['identifier'] id = file['identifier']
if file_map[id] if file_map[id]
file_map[id][:hidden] = true if get_bool_val(file, 'hidden', false) file_map[id][:hidden] = true if get_bool_val(file, 'hidden', false)
file_map[id][:locked] = true if get_bool_val(file, 'locked', false) file_map[id][:locked] = true if get_bool_val(file, 'locked', false)
if unlock_at = get_time_val(file, 'unlock_at') if (unlock_at = get_time_val(file, 'unlock_at'))
file_map[id][:unlock_at] = unlock_at file_map[id][:unlock_at] = unlock_at
end end
if lock_at = get_time_val(file, 'lock_at') if (lock_at = get_time_val(file, 'lock_at'))
file_map[id][:lock_at] = lock_at file_map[id][:lock_at] = lock_at
end end
if display_name = file.at_css("display_name") if (display_name = file.at_css("display_name"))
file_map[id][:display_name] = display_name.text file_map[id][:display_name] = display_name.text
end end
if usage_rights = file.at_css("usage_rights") if (usage_rights = file.at_css("usage_rights"))
rights_hash = { :use_justification => usage_rights.attr('use_justification') } rights_hash = { :use_justification => usage_rights.attr('use_justification') }
if legal_copyright = usage_rights.at_css('legal_copyright') if (legal_copyright = usage_rights.at_css('legal_copyright'))
rights_hash.merge!(:legal_copyright => legal_copyright.text) rights_hash.merge!(:legal_copyright => legal_copyright.text)
end end
if license = usage_rights.at_css('license') if (license = usage_rights.at_css('license'))
rights_hash.merge!(:license => license.text) rights_hash.merge!(:license => license.text)
end end
file_map[id][:usage_rights] = rights_hash file_map[id][:usage_rights] = rights_hash

View File

@ -51,7 +51,7 @@ module CC::Importer::Canvas
wiki[:url_name] = wiki_name wiki[:url_name] = wiki_name
wiki[:assignment] = nil wiki[:assignment] = nil
wiki[:todo_date] = meta['todo_date'] wiki[:todo_date] = meta['todo_date']
if asg_id = meta['assignment_identifier'] if (asg_id = meta['assignment_identifier'])
wiki[:assignment] = { wiki[:assignment] = {
migration_id: asg_id, migration_id: asg_id,
assignment_overrides: [], assignment_overrides: [],

View File

@ -23,7 +23,7 @@ module CC::Importer::Standard
def convert_cc_assignments(asmnts = []) def convert_cc_assignments(asmnts = [])
resources_by_type("assignment", "assignment_xmlv1p0").each do |res| resources_by_type("assignment", "assignment_xmlv1p0").each do |res|
if doc = get_node_or_open_file(res, 'assignment') if (doc = get_node_or_open_file(res, 'assignment'))
path = res[:href] || (res[:files] && res[:files].first && res[:files].first[:href]) path = res[:href] || (res[:files] && res[:files].first && res[:files].first[:href])
resource_dir = File.dirname(path) if path resource_dir = File.dirname(path) if path
@ -35,7 +35,7 @@ module CC::Importer::Standard
# FIXME check the XML namespace to make sure it's actually a canvas assignment # FIXME check the XML namespace to make sure it's actually a canvas assignment
# (blocked by remove_namespaces! in lib/canvas/migration/migrator.rb) # (blocked by remove_namespaces! in lib/canvas/migration/migrator.rb)
if assgn_node = doc.at_css('extensions > assignment') if (assgn_node = doc.at_css('extensions > assignment'))
parse_canvas_assignment_data(assgn_node, nil, asmnt) parse_canvas_assignment_data(assgn_node, nil, asmnt)
end end
@ -52,7 +52,7 @@ module CC::Importer::Standard
asmnt[:instructor_description] = get_node_val(doc, 'instructor_text') asmnt[:instructor_description] = get_node_val(doc, 'instructor_text')
asmnt[:title] = get_node_val(doc, 'title') asmnt[:title] = get_node_val(doc, 'title')
asmnt[:gradable] = get_bool_val(doc, 'gradable') asmnt[:gradable] = get_bool_val(doc, 'gradable')
if points_possible = get_node_att(doc, 'gradable', 'points_possible') if (points_possible = get_node_att(doc, 'gradable', 'points_possible'))
asmnt[:grading_type] = 'points' asmnt[:grading_type] = 'points'
asmnt[:points_possible] = points_possible.to_f asmnt[:points_possible] = points_possible.to_f
end end

View File

@ -118,7 +118,7 @@ module CC::Importer::Standard
def get_canvas_att_replacement_url(path, resource_dir = nil) def get_canvas_att_replacement_url(path, resource_dir = nil)
if path.start_with?('../') if path.start_with?('../')
if url = get_canvas_att_replacement_url(path.sub('../', ''), resource_dir) if (url = get_canvas_att_replacement_url(path.sub('../', ''), resource_dir))
return url return url
end end
end end
@ -131,7 +131,7 @@ module CC::Importer::Standard
unless mig_id unless mig_id
path = path.gsub(%r{\$[^$]*\$|\.\./}, '') path = path.gsub(%r{\$[^$]*\$|\.\./}, '')
if key = @file_path_migration_id.keys.detect { |k| k.end_with?(path) } if (key = @file_path_migration_id.keys.detect { |k| k.end_with?(path) })
mig_id = @file_path_migration_id[key] mig_id = @file_path_migration_id[key]
end end
end end
@ -170,7 +170,7 @@ module CC::Importer::Standard
begin begin
if val =~ FILEBASE_REGEX if val =~ FILEBASE_REGEX
val.gsub!(FILEBASE_REGEX, '') val.gsub!(FILEBASE_REGEX, '')
if new_url = get_canvas_att_replacement_url(val, resource_dir) if (new_url = get_canvas_att_replacement_url(val, resource_dir))
node[attr] = URI::escape(new_url) node[attr] = URI::escape(new_url)
if node.text.strip.blank? && !node.at_css("img") # add in the filename if the link is blank and doesn't have something visible like an image if node.text.strip.blank? && !node.at_css("img") # add in the filename if the link is blank and doesn't have something visible like an image
@ -179,7 +179,7 @@ module CC::Importer::Standard
end end
else else
if ImportedHtmlConverter.relative_url?(val) if ImportedHtmlConverter.relative_url?(val)
if new_url = get_canvas_att_replacement_url(val) if (new_url = get_canvas_att_replacement_url(val))
node[attr] = URI::escape(new_url) node[attr] = URI::escape(new_url)
end end
end end
@ -200,7 +200,7 @@ module CC::Importer::Standard
def convert_blti_links_with_flat(lti_converter) def convert_blti_links_with_flat(lti_converter)
tools = [] tools = []
resources_by_type("imsbasiclti").each do |res| resources_by_type("imsbasiclti").each do |res|
if doc = get_node_or_open_file(res) if (doc = get_node_or_open_file(res))
tool = lti_converter.convert_blti_link(doc) tool = lti_converter.convert_blti_link(doc)
tool[:migration_id] = res[:migration_id] tool[:migration_id] = res[:migration_id]
res[:url] = tool[:url] # for the organization item to reference res[:url] = tool[:url] # for the organization item to reference

View File

@ -28,7 +28,7 @@ module CC::Importer::Standard
resources_by_type("imsdt").each do |res| resources_by_type("imsdt").each do |res|
path = res[:href] || (res[:files] && res[:files].first && res[:files].first[:href]) path = res[:href] || (res[:files] && res[:files].first && res[:files].first[:href])
resource_dir = File.dirname(path) if path resource_dir = File.dirname(path) if path
if doc = get_node_or_open_file(res, TOPIC_NODE) if (doc = get_node_or_open_file(res, TOPIC_NODE))
topic = { :migration_id => res[:migration_id] } topic = { :migration_id => res[:migration_id] }
topic[:description] = get_node_val(doc, 'text') topic[:description] = get_node_val(doc, 'text')
topic[:description] = replace_urls(topic[:description]) topic[:description] = replace_urls(topic[:description])
@ -45,9 +45,9 @@ module CC::Importer::Standard
topic[:description] += "\n<li><a href=\"#{get_canvas_att_replacement_url(att_path, resource_dir) || att_path}\">#{File.basename att_path}</a>" topic[:description] += "\n<li><a href=\"#{get_canvas_att_replacement_url(att_path, resource_dir) || att_path}\">#{File.basename att_path}</a>"
end end
topic[:description] += "\n</ul>" topic[:description] += "\n</ul>"
elsif att_node = doc.at_css('attachment') elsif (att_node = doc.at_css('attachment'))
path = att_node['href'] path = att_node['href']
if id = find_file_migration_id(path) if (id = find_file_migration_id(path))
topic[:attachment_migration_id] = id topic[:attachment_migration_id] = id
end end
end end

View File

@ -31,7 +31,7 @@ module CC::Importer::Standard
doc.css('organizations organization > item > item').each do |item_node| doc.css('organizations organization > item > item').each do |item_node|
if item_node['identifierref'] if item_node['identifierref']
# item points to a single item # item points to a single item
if item = process_item(item_node, 0) if (item = process_item(item_node, 0))
if !misc_module if !misc_module
misc_module = { :title => "Misc Module", :migration_id => "misc_module_top_level_items", :items => [] } misc_module = { :title => "Misc Module", :migration_id => "misc_module_top_level_items", :items => [] }
modules << misc_module modules << misc_module
@ -69,7 +69,7 @@ module CC::Importer::Standard
else else
add_children(item_node, mod, indent + 1) add_children(item_node, mod, indent + 1)
end end
elsif item = process_item(item_node, indent) elsif (item = process_item(item_node, indent))
mod[:items] << item mod[:items] << item
end end
end end
@ -78,7 +78,7 @@ module CC::Importer::Standard
def process_item(item_node, indent) def process_item(item_node, indent)
item = nil item = nil
if resource = @resources[item_node['identifierref']] if (resource = @resources[item_node['identifierref']])
case resource[:type] case resource[:type]
when /assessment\z/ when /assessment\z/
item = { item = {
@ -101,7 +101,7 @@ module CC::Importer::Standard
item[:linked_resource_title] ||= title item[:linked_resource_title] ||= title
item = nil if item[:url].blank? item = nil if item[:url].blank?
when /\Aimsbasiclti/ when /\Aimsbasiclti/
if asmnt = find_assignment(resource[:migration_id]) if (asmnt = find_assignment(resource[:migration_id]))
item = { item = {
:indent => indent, :indent => indent,
:linked_resource_type => 'ASSIGNMENT', :linked_resource_type => 'ASSIGNMENT',

View File

@ -33,7 +33,7 @@ module CC::Importer::Standard
id = res[:migration_id] id = res[:migration_id]
if path.nil? # inline qti if path.nil? # inline qti
next unless res_node = @resource_nodes_for_flat_manifest[id] next unless (res_node = @resource_nodes_for_flat_manifest[id])
qti_node = res_node.elements.first qti_node = res_node.elements.first
path = "#{id}_qti.xml" path = "#{id}_qti.xml"
@ -45,10 +45,10 @@ module CC::Importer::Standard
qti_converted_dir = File.join(conversion_dir, id) qti_converted_dir = File.join(conversion_dir, id)
if run_qti_converter(full_path, qti_converted_dir, id) if run_qti_converter(full_path, qti_converted_dir, id)
# get quizzes/questions # get quizzes/questions
if q_list = convert_questions(qti_converted_dir, id) if (q_list = convert_questions(qti_converted_dir, id))
questions += q_list questions += q_list
end end
if quiz = convert_assessment(qti_converted_dir, id) if (quiz = convert_assessment(qti_converted_dir, id))
quizzes << quiz quizzes << quiz
end end
end end
@ -102,7 +102,7 @@ module CC::Importer::Standard
manifest_file = File.join(out_folder, Qti::Converter::MANIFEST_FILE) manifest_file = File.join(out_folder, Qti::Converter::MANIFEST_FILE)
quizzes = Qti.convert_assessments(manifest_file, :flavor => Qti::Flavors::COMMON_CARTRIDGE) quizzes = Qti.convert_assessments(manifest_file, :flavor => Qti::Flavors::COMMON_CARTRIDGE)
::Canvas::Migration::MigratorHelper.prepend_id_to_assessments(quizzes, resource_id) ::Canvas::Migration::MigratorHelper.prepend_id_to_assessments(quizzes, resource_id)
if quiz = quizzes.first if (quiz = quizzes.first)
quiz[:migration_id] = resource_id quiz[:migration_id] = resource_id
end end
rescue rescue

View File

@ -34,7 +34,7 @@ module CC::Importer::Standard
title = get_node_val(doc, 'webLink title') title = get_node_val(doc, 'webLink title')
url = get_node_att(doc, 'webLink url', 'href') url = get_node_att(doc, 'webLink url', 'href')
end end
elsif doc = get_node_or_open_file(resource, 'webLink') elsif (doc = get_node_or_open_file(resource, 'webLink'))
title = get_node_val(doc, 'title') title = get_node_val(doc, 'title')
url = get_node_att(doc, 'url', 'href') url = get_node_att(doc, 'url', 'href')
end end

View File

@ -133,7 +133,7 @@ module CC
end end
end end
if item.data && criterion = item.data[:rubric_criterion] if item.data && (criterion = item.data[:rubric_criterion])
out_node.points_possible criterion[:points_possible] if criterion[:points_possible] out_node.points_possible criterion[:points_possible] if criterion[:points_possible]
out_node.mastery_points criterion[:mastery_points] if criterion[:mastery_points] out_node.mastery_points criterion[:mastery_points] if criterion[:mastery_points]
if criterion[:ratings] && criterion[:ratings].length > 0 if criterion[:ratings] && criterion[:ratings].length > 0

View File

@ -323,7 +323,7 @@ module CC
pick_count = group['pick_count'].to_i pick_count = group['pick_count'].to_i
chosen = 0 chosen = 0
if group[:assessment_question_bank_id] if group[:assessment_question_bank_id]
if bank = @course.assessment_question_banks.where(id: group[:assessment_question_bank_id]).first if (bank = @course.assessment_question_banks.where(id: group[:assessment_question_bank_id]).first)
bank.assessment_questions.each do |question| bank.assessment_questions.each do |question|
# try adding questions until the pick count is reached # try adding questions until the pick count is reached
chosen += 1 if add_cc_question(node, question) chosen += 1 if add_cc_question(node, question)
@ -351,9 +351,9 @@ module CC
bank = nil bank = nil
if group[:assessment_question_bank_id] if group[:assessment_question_bank_id]
if bank = @course.assessment_question_banks.where(id: group[:assessment_question_bank_id]).first if (bank = @course.assessment_question_banks.where(id: group[:assessment_question_bank_id]).first)
sel_node.sourcebank_ref create_key(bank) sel_node.sourcebank_ref create_key(bank)
elsif bank = AssessmentQuestionBank.where(id: group[:assessment_question_bank_id]).first elsif (bank = AssessmentQuestionBank.where(id: group[:assessment_question_bank_id]).first)
sel_node.sourcebank_ref bank.id sel_node.sourcebank_ref bank.id
is_external = true is_external = true
end end

View File

@ -45,7 +45,7 @@ module CC
def add_ref_or_question(node, question) def add_ref_or_question(node, question)
aq = nil aq = nil
unless question[:assessment_question_id].blank? unless question[:assessment_question_id].blank?
if aq = AssessmentQuestion.where(id: question[:assessment_question_id]).first if (aq = AssessmentQuestion.where(id: question[:assessment_question_id]).first)
if aq.deleted? || if aq.deleted? ||
!aq.assessment_question_bank || !aq.assessment_question_bank ||
aq.assessment_question_bank.deleted? || aq.assessment_question_bank.deleted? ||
@ -440,7 +440,7 @@ module CC
correct_points = "%.2f" % correct_points correct_points = "%.2f" % correct_points
groups.each_pair do |id, answers| groups.each_pair do |id, answers|
if answer = answers.find { |a| a['weight'].to_i > 0 } if (answer = answers.find { |a| a['weight'].to_i > 0 })
node.respcondition do |r_node| node.respcondition do |r_node|
r_node.conditionvar do |c_node| r_node.conditionvar do |c_node|
c_node.varequal(answer['id'], :respident => "response_#{id}") c_node.varequal(answer['id'], :respident => "response_#{id}")

View File

@ -94,7 +94,7 @@ module CC
c_node.long_description criterion[:long_description] if criterion[:long_description].present? c_node.long_description criterion[:long_description] if criterion[:long_description].present?
c_node.criterion_use_range criterion[:criterion_use_range] if criterion[:criterion_use_range].present? c_node.criterion_use_range criterion[:criterion_use_range] if criterion[:criterion_use_range].present?
if criterion[:learning_outcome_id].present? if criterion[:learning_outcome_id].present?
if lo = @course.available_outcome(criterion[:learning_outcome_id]) if (lo = @course.available_outcome(criterion[:learning_outcome_id]))
if lo.context_type == "Course" && lo.context_id == @course.id if lo.context_type == "Course" && lo.context_id == @course.id
c_node.learning_outcome_identifierref create_key(lo) c_node.learning_outcome_identifierref create_key(lo)
else else

View File

@ -234,7 +234,7 @@ module CC
# download from kaltura if the file wasn't already exported here in add_course_files # download from kaltura if the file wasn't already exported here in add_course_files
if !@added_attachments || @added_attachments[obj.attachment_id] != path if !@added_attachments || @added_attachments[obj.attachment_id] != path
unless CanvasKaltura::ClientV3::ASSET_STATUSES[info[:asset][:status]] == :READY && unless CanvasKaltura::ClientV3::ASSET_STATUSES[info[:asset][:status]] == :READY &&
url = (client.flavorAssetGetPlaylistUrl(obj.media_id, info[:asset][:id]) || client.flavorAssetGetDownloadUrl(info[:asset][:id])) (url = (client.flavorAssetGetPlaylistUrl(obj.media_id, info[:asset][:id]) || client.flavorAssetGetDownloadUrl(info[:asset][:id])))
add_error(I18n.t('course_exports.errors.media_file', "A media file failed to export")) add_error(I18n.t('course_exports.errors.media_file', "A media file failed to export"))
next next
end end

View File

@ -214,7 +214,7 @@ class CourseLinkValidator
def find_invalid_link(url) def find_invalid_link(url)
return if url.start_with?('mailto:') return if url.start_with?('mailto:')
unless result = self.visited_urls[url] unless (result = self.visited_urls[url])
begin begin
if ImportedHtmlConverter.relative_url?(url) || (self.domain_regex && url.match(self.domain_regex)) if ImportedHtmlConverter.relative_url?(url) || (self.domain_regex && url.match(self.domain_regex))
if valid_route?(url) if valid_route?(url)

View File

@ -119,7 +119,7 @@ class CutyCapt
end end
def self.snapshot_url(url, &block) def self.snapshot_url(url, &block)
return nil unless config = self.config return nil unless (config = self.config)
return nil unless self.verify_url(url) return nil unless self.verify_url(url)
format = "png" format = "png"

View File

@ -227,7 +227,7 @@ module DatesOverridable
hash.merge!({ :all_day => assignment.all_day, :all_day_date => assignment.all_day_date }) hash.merge!({ :all_day => assignment.all_day, :all_day_date => assignment.all_day_date })
end end
if @applied_overrides && override = @applied_overrides.find { |o| o.due_at == due_at } if @applied_overrides && (override = @applied_overrides.find { |o| o.due_at == due_at })
hash[:override] = override hash[:override] = override
hash[:title] = override.title hash[:title] = override.title
hash[:set_type] = override.set_type hash[:set_type] = override.set_type
@ -255,7 +255,7 @@ module DatesOverridable
elsif self.multiple_due_dates_apply_to?(user) elsif self.multiple_due_dates_apply_to?(user)
hash[:vdd_tooltip] = OverrideTooltipPresenter.new(self, user).as_json hash[:vdd_tooltip] = OverrideTooltipPresenter.new(self, user).as_json
else else
if due_date = self.overridden_for(user).due_at if (due_date = self.overridden_for(user).due_at)
hash[:due_date] = due_date hash[:due_date] = due_date
elsif user_is_admin && (due_date = all_due_dates.dig(0, :due_at)) elsif user_is_admin && (due_date = all_due_dates.dig(0, :due_at))
hash[:due_date] = due_date hash[:due_date] = due_date

View File

@ -231,6 +231,7 @@ class GradebookImporter
@assignments.each_with_index do |assignment, idx| @assignments.each_with_index do |assignment, idx|
next if assignment.changed? && !readonly_assignment?(assignment) next if assignment.changed? && !readonly_assignment?(assignment)
# rubocop:disable Lint/AssignmentInCondition https://github.com/rubocop/rubocop/issues/10136
indexes_to_delete << idx if readonly_assignment?(assignment) || @students.all? do |student| indexes_to_delete << idx if readonly_assignment?(assignment) || @students.all? do |student|
submission = @gradebook_importer_assignments[student.id][idx] submission = @gradebook_importer_assignments[student.id][idx]
@ -243,6 +244,7 @@ class GradebookImporter
no_change || !submission['gradeable'] no_change || !submission['gradeable']
end end
# rubocop:enable Lint/AssignmentInCondition
end end
custom_column_ids_to_skip_on_import = [] custom_column_ids_to_skip_on_import = []

View File

@ -41,7 +41,7 @@ module LocaleSelection
-> { Account.recursive_default_locale_for_id(context.id) if context.try(:is_a?, Account) }, -> { Account.recursive_default_locale_for_id(context.id) if context.try(:is_a?, Account) },
-> { root_account.try(:default_locale) }, -> { root_account.try(:default_locale) },
-> { -> {
if accept_language && locale = infer_browser_locale(accept_language, LocaleSelection.locales_with_aliases) if accept_language && (locale = infer_browser_locale(accept_language, LocaleSelection.locales_with_aliases))
GuardRail.activate(:primary) do GuardRail.activate(:primary) do
user.update_attribute(:browser_locale, locale) if user && user.browser_locale != locale user.update_attribute(:browser_locale, locale) if user && user.browser_locale != locale
end end
@ -84,7 +84,7 @@ module LocaleSelection
# en-US range is a longer match, so it loses) # en-US range is a longer match, so it loses)
best_locales = supported_locales.inject([]) { |ary, locale| best_locales = supported_locales.inject([]) { |ary, locale|
if best_range = ranges.detect { |r, q| r + '-' == (locale.downcase + '-')[0..r.size] || r == '*' } 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 ary << [locale, best_range.last, ranges.index(best_range)] unless best_range.last == 0
end end
ary ary

View File

@ -42,7 +42,7 @@ module Lti
end end
def authenticate_body_hash def authenticate_body_hash
if body_hash = OAuth::Helper.parse_header(request.authorization)['oauth_body_hash'] if (body_hash = OAuth::Helper.parse_header(request.authorization)['oauth_body_hash'])
request.body.rewind request.body.rewind
generated_hash = Digest::SHA1.base64digest(request.body.read) generated_hash = Digest::SHA1.base64digest(request.body.read)
request.body.rewind # Be Kind Rewind request.body.rewind # Be Kind Rewind

View File

@ -126,25 +126,21 @@ class MessageableUser < User
# common_groups # common_groups
def populate_common_contexts def populate_common_contexts
@global_common_courses = {} @global_common_courses = {}
if common_courses = read_attribute(:common_courses) read_attribute(:common_courses)&.to_s&.split(',')&.each do |common_course|
common_courses.to_s.split(',').each do |common_course| course_id, role = common_course.split(':')
course_id, role = common_course.split(':') course_id = course_id.to_i
course_id = course_id.to_i # a course id of 0 indicates admin visibility without an actual shared
# a course id of 0 indicates admin visibility without an actual shared # course; don't "globalize" it
# course; don't "globalize" it course_id = Shard.global_id_for(course_id) unless course_id.zero?
course_id = Shard.global_id_for(course_id) unless course_id.zero? @global_common_courses[course_id] ||= []
@global_common_courses[course_id] ||= [] @global_common_courses[course_id] << role
@global_common_courses[course_id] << role
end
end end
@global_common_groups = {} @global_common_groups = {}
if common_groups = read_attribute(:common_groups) read_attribute(:common_groups)&.to_s&.split(',')&.each do |group_id|
common_groups.to_s.split(',').each do |group_id| group_id = Shard.global_id_for(group_id.to_i)
group_id = Shard.global_id_for(group_id.to_i) @global_common_groups[group_id] ||= []
@global_common_groups[group_id] ||= [] @global_common_groups[group_id] << 'Member'
@global_common_groups[group_id] << 'Member'
end
end end
end end
after_find :populate_common_contexts after_find :populate_common_contexts

View File

@ -295,7 +295,7 @@ class MessageableUser
# skipping messageability constraints, do I see the user in that specific # skipping messageability constraints, do I see the user in that specific
# course, and if so with which enrollment type(s)? # course, and if so with which enrollment type(s)?
if include_course_id && course = Course.where(id: include_course_id).first if include_course_id && (course = Course.where(id: include_course_id).first)
missing_users = users.reject { |user| user.global_common_courses.keys.include?(course.global_id) } missing_users = users.reject { |user| user.global_common_courses.keys.include?(course.global_id) }
if missing_users.present? if missing_users.present?
course.shard.activate do course.shard.activate do
@ -348,7 +348,7 @@ class MessageableUser
# skipping messageability constraints, do I see the user in that specific # skipping messageability constraints, do I see the user in that specific
# group? # group?
if include_group_id && group = Group.where(id: include_group_id).first if include_group_id && (group = Group.where(id: include_group_id).first)
missing_users = users.reject { |user| user.global_common_groups.keys.include?(group.global_id) } missing_users = users.reject { |user| user.global_common_groups.keys.include?(group.global_id) }
if missing_users.present? if missing_users.present?
group.shard.activate do group.shard.activate do
@ -427,7 +427,7 @@ class MessageableUser
course.shard.activate do course.shard.activate do
# make sure the course is recognized # make sure the course is recognized
return unless options[:admin_context] || course = course_index[course.id] return unless options[:admin_context] || (course = course_index[course.id])
scope = enrollment_scope(options.merge( scope = enrollment_scope(options.merge(
:include_concluded_students => false, :include_concluded_students => false,

View File

@ -68,7 +68,7 @@ module ModelCache
module InstanceMethods module InstanceMethods
def add_to_caches def add_to_caches
return unless cache = ModelCache[self.class.name.underscore.pluralize.to_sym] return unless (cache = ModelCache[self.class.name.underscore.pluralize.to_sym])
cache.keys.each do |key| cache.keys.each do |key|
cache[key][send(key)] = self cache[key][send(key)] = self
@ -76,7 +76,7 @@ module ModelCache
end end
def update_in_caches def update_in_caches
return unless cache = ModelCache[self.class.name.underscore.pluralize.to_sym] return unless (cache = ModelCache[self.class.name.underscore.pluralize.to_sym])
cache.keys.each do |key| cache.keys.each do |key|
if saved_change_to_attribute?(key) if saved_change_to_attribute?(key)

View File

@ -94,11 +94,11 @@ module Reporting
private private
def save_detailed_progressive(account, data) def save_detailed_progressive(account, data)
if snapshot = account.report_snapshots.progressive.last progressive = if (snapshot = account.report_snapshots.progressive.last)
progressive = snapshot.data.with_indifferent_access snapshot.data.with_indifferent_access
else else
progressive = new_progressive_hash.with_indifferent_access new_progressive_hash.with_indifferent_access
end end
progressive[:generated_at] = @timestamp progressive[:generated_at] = @timestamp
create_progressive_hashes(progressive, data) create_progressive_hashes(progressive, data)

View File

@ -20,11 +20,7 @@
module SimpleTags module SimpleTags
module ReaderInstanceMethods module ReaderInstanceMethods
def tags def tags
@tag_array ||= if tags = read_attribute(:tags) @tag_array ||= read_attribute(:tags)&.split(',') || []
tags.split(',')
else
[]
end
end end
def serialized_tags(tags = self.tags) def serialized_tags(tags = self.tags)

View File

@ -4,7 +4,7 @@ namespace :brand_configs do
desc "Writes the .css (css variables), .js & .json files that are used to load the theme editor variables for each brand " + desc "Writes the .css (css variables), .js & .json files that are used to load the theme editor variables for each brand " +
"Set BRAND_CONFIG_MD5=<whatever> to save just that one, otherwise writes a file for each BrandConfig in db." "Set BRAND_CONFIG_MD5=<whatever> to save just that one, otherwise writes a file for each BrandConfig in db."
task :write => :environment do task :write => :environment do
if md5 = ENV['BRAND_CONFIG_MD5'] if (md5 = ENV['BRAND_CONFIG_MD5'])
BrandConfig.find(md5).save_all_files! BrandConfig.find(md5).save_all_files!
else else
BrandConfig.clean_unused_from_db! BrandConfig.clean_unused_from_db!

View File

@ -27,7 +27,7 @@ namespace :canvas do
require 'json' require 'json'
require 'benchmark' require 'benchmark'
unless out_path = args[:out] unless (out_path = args[:out])
raise "Missing path to output file." raise "Missing path to output file."
end end

View File

@ -207,11 +207,11 @@ class UnzipAttachment
# For every directory in the path... # For every directory in the path...
# (-2 means all entries but the last, which should be a filename) # (-2 means all entries but the last, which should be a filename)
list[0..-2].each do |dir| list[0..-2].each do |dir|
if new_dir = current.sub_folders.where(name: dir).first current = if (new_dir = current.sub_folders.where(name: dir).first)
current = new_dir new_dir
else else
current = assert_folder(current, dir) assert_folder(current, dir)
end end
end end
current current
end end

View File

@ -226,7 +226,7 @@ module UserContent
end end
end end
if module_item = rest.try(:match, %r{/items/(\d+)}) if (module_item = rest.try(:match, %r{/items/(\d+)}))
type = 'items' type = 'items'
obj_id = module_item[1].to_i obj_id = module_item[1].to_i
end end

View File

@ -137,7 +137,7 @@ class UserListV2
@addresses.each do |a| @addresses.each do |a|
address = @lowercase ? a[:address].downcase : a[:address] address = @lowercase ? a[:address].downcase : a[:address]
unless grouped_results.key?(address) unless grouped_results.key?(address)
if name = a.delete(:name) if (name = a.delete(:name))
a[:user_name] = name a[:user_name] = name
end end
@missing_results << a @missing_results << a

View File

@ -237,7 +237,7 @@ class UserMerge
end end
end end
if existing_record = target_values[[key, sub_key]] if (existing_record = target_values[[key, sub_key]])
existing_record_updates[existing_record] = value existing_record_updates[existing_record] = value
else else
new_record_hashes << { :user_id => target_user.id, :key => key, :sub_key => sub_key&.to_json, :value => value.to_yaml } new_record_hashes << { :user_id => target_user.id, :key => key, :sub_key => sub_key&.to_json, :value => value.to_yaml }
@ -389,7 +389,7 @@ class UserMerge
if from_user.shard != target_user.shard if from_user.shard != target_user.shard
User.clone_communication_channel(source_cc, target_user, max_position) User.clone_communication_channel(source_cc, target_user, max_position)
end end
elsif to_retire = source_cc elsif (to_retire = source_cc)
# retired, retired # retired, retired
end end
to_retire to_retire

View File

@ -62,23 +62,23 @@ describe "AuthenticationAudit API", type: :request do
end end
def fetch_for_context(context, options = {}) def fetch_for_context(context, options = {})
type = context.class.to_s.downcase unless type = options.delete(:type) type = context.class.to_s.downcase unless (type = options.delete(:type))
id = context.id.to_s id = context.id.to_s
arguments = { controller: 'authentication_audit_api', action: "for_#{type}", :"#{type}_id" => id, format: 'json' } arguments = { controller: 'authentication_audit_api', action: "for_#{type}", :"#{type}_id" => id, format: 'json' }
query_string = [] query_string = []
if per_page = options.delete(:per_page) if (per_page = options.delete(:per_page))
arguments[:per_page] = per_page.to_s arguments[:per_page] = per_page.to_s
query_string << "per_page=#{arguments[:per_page]}" query_string << "per_page=#{arguments[:per_page]}"
end end
if start_time = options.delete(:start_time) if (start_time = options.delete(:start_time))
arguments[:start_time] = start_time.iso8601 arguments[:start_time] = start_time.iso8601
query_string << "start_time=#{arguments[:start_time]}" query_string << "start_time=#{arguments[:start_time]}"
end end
if end_time = options.delete(:end_time) if (end_time = options.delete(:end_time))
arguments[:end_time] = end_time.iso8601 arguments[:end_time] = end_time.iso8601
query_string << "end_time=#{arguments[:end_time]}" query_string << "end_time=#{arguments[:end_time]}"
end end

View File

@ -56,28 +56,28 @@ describe "CourseAudit API", type: :request do
end end
def fetch_for_context(context, id: nil, **options) def fetch_for_context(context, id: nil, **options)
type = context.class.to_s.downcase unless type = options.delete(:type) type = context.class.to_s.downcase unless (type = options.delete(:type))
id ||= context.id.to_s id ||= context.id.to_s
arguments = { controller: 'course_audit_api', action: "for_#{type}", :"#{type}_id" => id, format: 'json' } arguments = { controller: 'course_audit_api', action: "for_#{type}", :"#{type}_id" => id, format: 'json' }
query_string = [] query_string = []
if per_page = options.delete(:per_page) if (per_page = options.delete(:per_page))
arguments[:per_page] = per_page.to_s arguments[:per_page] = per_page.to_s
query_string << "per_page=#{arguments[:per_page]}" query_string << "per_page=#{arguments[:per_page]}"
end end
if start_time = options.delete(:start_time) if (start_time = options.delete(:start_time))
arguments[:start_time] = start_time.iso8601 arguments[:start_time] = start_time.iso8601
query_string << "start_time=#{arguments[:start_time]}" query_string << "start_time=#{arguments[:start_time]}"
end end
if end_time = options.delete(:end_time) if (end_time = options.delete(:end_time))
arguments[:end_time] = end_time.iso8601 arguments[:end_time] = end_time.iso8601
query_string << "end_time=#{arguments[:end_time]}" query_string << "end_time=#{arguments[:end_time]}"
end end
if account = options.delete(:account) if (account = options.delete(:account))
arguments[:account_id] = Shard.global_id_for(account).to_s arguments[:account_id] = Shard.global_id_for(account).to_s
query_string << "account_id=#{arguments[:account_id]}" query_string << "account_id=#{arguments[:account_id]}"
end end

View File

@ -56,29 +56,29 @@ describe "GradeChangeAudit API", type: :request do
end end
def fetch_for_context(context, options = {}) def fetch_for_context(context, options = {})
type = context.class.to_s.downcase unless type = options.delete(:type) type = context.class.to_s.downcase unless (type = options.delete(:type))
user = options.delete(:user) || @viewing_user user = options.delete(:user) || @viewing_user
id = Shard.global_id_for(context).to_s id = Shard.global_id_for(context).to_s
arguments = { controller: :grade_change_audit_api, action: "for_#{type}", "#{type}_id": id, format: :json } arguments = { controller: :grade_change_audit_api, action: "for_#{type}", "#{type}_id": id, format: :json }
query_string = [] query_string = []
if per_page = options.delete(:per_page) if (per_page = options.delete(:per_page))
arguments[:per_page] = per_page.to_s arguments[:per_page] = per_page.to_s
query_string << "per_page=#{arguments[:per_page]}" query_string << "per_page=#{arguments[:per_page]}"
end end
if start_time = options.delete(:start_time) if (start_time = options.delete(:start_time))
arguments[:start_time] = start_time.iso8601 arguments[:start_time] = start_time.iso8601
query_string << "start_time=#{arguments[:start_time]}" query_string << "start_time=#{arguments[:start_time]}"
end end
if end_time = options.delete(:end_time) if (end_time = options.delete(:end_time))
arguments[:end_time] = end_time.iso8601 arguments[:end_time] = end_time.iso8601
query_string << "end_time=#{arguments[:end_time]}" query_string << "end_time=#{arguments[:end_time]}"
end end
if account = options.delete(:account) if (account = options.delete(:account))
arguments[:account_id] = Shard.global_id_for(account).to_s arguments[:account_id] = Shard.global_id_for(account).to_s
query_string << "account_id=#{arguments[:account_id]}" query_string << "account_id=#{arguments[:account_id]}"
end end

View File

@ -73,7 +73,7 @@ describe "Outcomes API", type: :request do
retval["points_possible"] = presets[:points_possible] || proficiency.points_possible retval["points_possible"] = presets[:points_possible] || proficiency.points_possible
retval["mastery_points"] = presets[:mastery_points] || proficiency.mastery_points retval["mastery_points"] = presets[:mastery_points] || proficiency.mastery_points
retval["ratings"] = presets[:ratings] || proficiency.ratings_hash.map(&:stringify_keys) retval["ratings"] = presets[:ratings] || proficiency.ratings_hash.map(&:stringify_keys)
elsif criterion = (outcome.data && outcome.data[:rubric_criterion]) elsif (criterion = outcome.data && outcome.data[:rubric_criterion])
retval["points_possible"] = presets[:points_possible] || criterion[:points_possible].to_i retval["points_possible"] = presets[:points_possible] || criterion[:points_possible].to_i
retval["mastery_points"] = presets[:mastery_points] || criterion[:mastery_points].to_i retval["mastery_points"] = presets[:mastery_points] || criterion[:mastery_points].to_i
retval["ratings"] = presets[:ratings] || criterion[:ratings].map(&:stringify_keys) retval["ratings"] = presets[:ratings] || criterion[:ratings].map(&:stringify_keys)

View File

@ -93,7 +93,7 @@ module Factories
if opts[:role_changes] if opts[:role_changes]
opts[:role_changes].each_pair do |permission, enabled| opts[:role_changes].each_pair do |permission, enabled|
role = opts[:role] || admin_role role = opts[:role] || admin_role
if ro = account.role_overrides.where(:permission => permission.to_s, :role_id => role.id).first if (ro = account.role_overrides.where(:permission => permission.to_s, :role_id => role.id).first)
ro.update_attribute(:enabled, enabled) ro.update_attribute(:enabled, enabled)
else else
account.role_overrides.create(:permission => permission.to_s, :enabled => enabled, :role => role) account.role_overrides.create(:permission => permission.to_s, :enabled => enabled, :role => role)

View File

@ -50,7 +50,7 @@ module Factories
def appointment_group_model(opts = {}) def appointment_group_model(opts = {})
@course ||= opts.delete(:course) || course_model @course ||= opts.delete(:course) || course_model
if sub_context = opts.delete(:sub_context) if (sub_context = opts.delete(:sub_context))
opts[:sub_context_codes] = [sub_context.asset_string] opts[:sub_context_codes] = [sub_context.asset_string]
end end
@appointment_group = AppointmentGroup.create!(valid_appointment_group_attributes.merge(opts)) @appointment_group = AppointmentGroup.create!(valid_appointment_group_attributes.merge(opts))

View File

@ -158,7 +158,7 @@ module Factories
if options[:account_associations] if options[:account_associations]
create_records(CourseAccountAssociation, course_ids.map { |id| { account_id: account.id, course_id: id, depth: 0, root_account_id: account.resolved_root_account_id, created_at: now, updated_at: now } }) create_records(CourseAccountAssociation, course_ids.map { |id| { account_id: account.id, course_id: id, depth: 0, root_account_id: account.resolved_root_account_id, created_at: now, updated_at: now } })
end end
if user = options[:enroll_user] if (user = options[:enroll_user])
section_ids = create_records(CourseSection, course_ids.map { |id| { course_id: id, root_account_id: account.id, name: "Default Section", default_section: true, created_at: now, updated_at: now } }) section_ids = create_records(CourseSection, course_ids.map { |id| { course_id: id, root_account_id: account.id, name: "Default Section", default_section: true, created_at: now, updated_at: now } })
type = options[:enrollment_type] || "TeacherEnrollment" type = options[:enrollment_type] || "TeacherEnrollment"
role_id = Role.get_built_in_role(type, root_account_id: account.resolved_root_account_id).id role_id = Role.get_built_in_role(type, root_account_id: account.resolved_root_account_id).id

View File

@ -43,7 +43,7 @@ module RspecMockAnyInstantiation
end end
def instantiate(record, column_types = {}, &block) def instantiate(record, column_types = {}, &block)
if obj = @@any_instantiation[[base_class, record['id'].to_i]] if (obj = @@any_instantiation[[base_class, record['id'].to_i]])
obj obj
else else
super super
@ -51,7 +51,7 @@ module RspecMockAnyInstantiation
end end
def instantiate_instance_of(klass, record, column_types = {}, &block) def instantiate_instance_of(klass, record, column_types = {}, &block)
if obj = @@any_instantiation[[klass, record['id'].to_i]] if (obj = @@any_instantiation[[klass, record['id'].to_i]])
obj obj
else else
super super

View File

@ -203,7 +203,7 @@ module ConversationsCommon
end end
def run_progress_job def run_progress_job
return unless progress = Progress.where(tag: 'conversation_batch_update').first return unless (progress = Progress.where(tag: 'conversation_batch_update').first)
job = Delayed::Job.find(progress.delayed_job_id) job = Delayed::Job.find(progress.delayed_job_id)
job.invoke_job job.invoke_job

View File

@ -260,9 +260,7 @@ describe "users" do
end end
it "requires terms if configured to do so" do it "requires terms if configured to do so" do
if terms = Account.default.terms_of_service Account.default.terms_of_service&.update(passive: false)
terms.update(passive: false)
end
get "/register" get "/register"
@ -279,9 +277,7 @@ describe "users" do
end end
it "registers a student with a join code" do it "registers a student with a join code" do
if terms = Account.default.terms_of_service Account.default.terms_of_service&.update(passive: false)
terms.update(passive: false)
end
Account.default.allow_self_enrollment! Account.default.allow_self_enrollment!
course_factory(active_all: true) course_factory(active_all: true)
@ -305,9 +301,7 @@ describe "users" do
end end
it "registers a teacher" do it "registers a teacher" do
if terms = Account.default.terms_of_service Account.default.terms_of_service&.update(passive: false)
terms.update(passive: false)
end
get '/register' get '/register'
f('#signup_teacher').click f('#signup_teacher').click
@ -338,9 +332,7 @@ describe "users" do
end end
it "registers an observer" do it "registers an observer" do
if terms = Account.default.terms_of_service Account.default.terms_of_service&.update(passive: false)
terms.update(passive: false)
end
user = user_with_pseudonym(:active_all => true, :password => 'lolwut12') user = user_with_pseudonym(:active_all => true, :password => 'lolwut12')
pairing_code = user.generate_observer_pairing_code pairing_code = user.generate_observer_pairing_code

View File

@ -662,7 +662,7 @@ RSpec.configure do |config|
def as(ancestor) def as(ancestor)
@__as ||= {} @__as ||= {}
unless r = @__as[ancestor] unless (r = @__as[ancestor])
r = (@__as[ancestor] = As.new(self, ancestor)) r = (@__as[ancestor] = As.new(self, ancestor))
end end
r r
@ -723,12 +723,12 @@ RSpec.configure do |config|
end end
def run_jobs def run_jobs
while job = Delayed::Job.get_and_lock_next_available( while (job = Delayed::Job.get_and_lock_next_available(
'spec run_jobs', 'spec run_jobs',
Delayed::Settings.queue, Delayed::Settings.queue,
0, 0,
Delayed::MAX_PRIORITY Delayed::MAX_PRIORITY
) ))
run_job(job) run_job(job)
end end
end end