From ff99d1813848f2b926ddb4d62e9cef1b8d0fb2dd Mon Sep 17 00:00:00 2001 From: Cody Cutrer Date: Sat, 20 Nov 2021 07:04:59 -0700 Subject: [PATCH] RuboCop: Style/RedundantSelf [skip-stages=Flakey] auto-corrected Change-Id: I5f26ad1f8210a74c2198b514235d5134dcd0dae1 Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/279070 Reviewed-by: Jacob Burroughs QA-Review: Cody Cutrer Product-Review: Cody Cutrer Migration-Review: Cody Cutrer Tested-by: Service Cloud Jenkins --- .rubocop.common.yml | 4 +- app/controllers/application_controller.rb | 10 +- app/controllers/assignments_controller.rb | 2 +- .../context_modules_api_controller.rb | 2 +- app/controllers/gradebooks_controller.rb | 2 +- .../lti/concerns/sessionless_launches.rb | 2 +- app/controllers/media_objects_controller.rb | 4 +- app/controllers/outcome_results_controller.rb | 4 +- app/controllers/release_notes_controller.rb | 4 +- app/controllers/user_notes_controller.rb | 2 +- app/graphql/graphql_helpers.rb | 4 +- app/graphql/graphql_postgres_timeout.rb | 2 +- .../mutations/add_conversation_message.rb | 2 +- app/graphql/mutations/update_assignment.rb | 2 +- .../types/communication_channel_type.rb | 2 +- app/helpers/application_helper.rb | 4 +- app/helpers/attachment_helper.rb | 4 +- app/helpers/datadog_rum_helper.rb | 2 +- app/helpers/search_helper.rb | 2 +- app/middleware/request_throttle.rb | 4 +- app/models/access_token.rb | 8 +- app/models/account.rb | 326 +++++----- app/models/account/settings.rb | 16 +- app/models/account_notification.rb | 48 +- app/models/account_notification_role.rb | 6 +- app/models/account_report.rb | 20 +- app/models/account_report_runner.rb | 10 +- app/models/account_user.rb | 42 +- app/models/alert.rb | 12 +- app/models/alerts/delayed_alert_sender.rb | 2 +- app/models/announcement.rb | 36 +- app/models/anonymous_or_moderation_event.rb | 2 +- app/models/appointment_group.rb | 8 +- app/models/assessment_question.rb | 36 +- app/models/assessment_question_bank.rb | 42 +- app/models/assessment_request.rb | 32 +- app/models/asset_user_access.rb | 44 +- app/models/asset_user_access_log.rb | 52 +- app/models/assignment.rb | 458 +++++++------- app/models/assignment_group.rb | 66 +- app/models/assignment_override.rb | 34 +- app/models/assignment_override_student.rb | 2 +- app/models/assignment_student_visibility.rb | 2 +- app/models/attachment.rb | 314 +++++----- .../auditors/active_record/course_record.rb | 2 +- app/models/auditors/course.rb | 28 +- app/models/authentication_provider.rb | 12 +- .../authentication_provider/delegated.rb | 6 +- app/models/authentication_provider/ldap.rb | 68 +-- app/models/authentication_provider/saml.rb | 8 +- app/models/big_blue_button_conference.rb | 12 +- app/models/bookmark_service.rb | 4 +- app/models/bounce_notification_processor.rb | 6 +- app/models/brand_config.rb | 8 +- app/models/calendar_event.rb | 52 +- app/models/canvadoc.rb | 8 +- app/models/canvadocs_annotation_context.rb | 4 +- app/models/collaboration.rb | 30 +- app/models/collaborator.rb | 10 +- app/models/comment_bank_item.rb | 2 +- app/models/communication_channel.rb | 94 +-- .../assignment_set_action.rb | 2 +- .../assignment_set_association.rb | 8 +- app/models/conditional_release/rule.rb | 6 +- app/models/conditional_release/service.rb | 2 +- app/models/content_export.rb | 130 ++-- app/models/content_migration.rb | 214 +++---- app/models/content_participation.rb | 2 +- app/models/content_participation_count.rb | 8 +- app/models/content_share.rb | 8 +- app/models/content_tag.rb | 170 +++--- app/models/context.rb | 32 +- app/models/context_external_tool.rb | 64 +- app/models/context_module.rb | 232 +++---- app/models/context_module_item.rb | 4 +- app/models/context_module_progression.rb | 86 +-- app/models/conversation.rb | 70 +-- app/models/conversation_batch.rb | 12 +- app/models/conversation_message.rb | 60 +- .../conversation_message_participant.rb | 2 +- app/models/conversation_participant.rb | 40 +- app/models/course.rb | 572 +++++++++--------- app/models/course_account_association.rb | 4 +- app/models/course_section.rb | 124 ++-- app/models/courses/item_visibility_helper.rb | 2 +- app/models/crocodoc_document.rb | 6 +- app/models/csp/account_helper.rb | 38 +- app/models/csp/course_helper.rb | 16 +- app/models/csp/domain.rb | 10 +- app/models/custom_data.rb | 6 +- app/models/delayed_message.rb | 10 +- app/models/delayed_notification.rb | 6 +- app/models/developer_key.rb | 26 +- app/models/developer_key_account_binding.rb | 2 +- app/models/discussion_entry.rb | 158 +++-- app/models/discussion_entry_participant.rb | 18 +- app/models/discussion_topic.rb | 506 ++++++++-------- .../discussion_topic/materialized_view.rb | 38 +- app/models/discussion_topic_participant.rb | 2 +- .../discussion_topic_section_visibility.rb | 16 +- app/models/enrollment.rb | 294 +++++---- app/models/enrollment_dates_override.rb | 4 +- app/models/enrollment_state.rb | 62 +- app/models/enrollment_term.rb | 34 +- app/models/eportfolio.rb | 24 +- app/models/eportfolio_category.rb | 8 +- app/models/eportfolio_entry.rb | 38 +- app/models/epub_export.rb | 10 +- app/models/error_report.rb | 8 +- app/models/etherpad_collaboration.rb | 2 +- app/models/external_feed.rb | 42 +- app/models/external_feed_entry.rb | 4 +- app/models/external_integration_key.rb | 6 +- app/models/favorite.rb | 2 +- app/models/feature_flag.rb | 8 +- app/models/folder.rb | 116 ++-- app/models/google_docs_collaboration.rb | 26 +- app/models/grading_period.rb | 4 +- app/models/grading_period_group.rb | 2 +- app/models/grading_standard.rb | 30 +- app/models/group.rb | 214 +++---- app/models/group_and_membership_importer.rb | 4 +- app/models/group_category.rb | 60 +- app/models/group_membership.rb | 82 +-- app/models/importers.rb | 8 +- .../importers/assessment_question_importer.rb | 4 +- .../importers/assignment_group_importer.rb | 2 +- app/models/importers/assignment_importer.rb | 2 +- .../importers/calendar_event_importer.rb | 2 +- .../context_external_tool_importer.rb | 10 +- .../importers/context_module_importer.rb | 20 +- .../importers/course_content_importer.rb | 8 +- .../importers/discussion_topic_importer.rb | 4 +- .../importers/external_feed_importer.rb | 2 +- .../importers/grading_standard_importer.rb | 2 +- app/models/importers/group_importer.rb | 2 +- app/models/importers/pace_plan_importer.rb | 2 +- app/models/importers/quiz_importer.rb | 2 +- .../importers/quiz_question_importer.rb | 6 +- app/models/importers/rubric_importer.rb | 2 +- app/models/importers/wiki_page_importer.rb | 4 +- app/models/learning_outcome.rb | 70 +-- app/models/learning_outcome_group.rb | 36 +- .../learning_outcome_question_result.rb | 30 +- app/models/learning_outcome_result.rb | 68 +-- app/models/live_assessments/assessment.rb | 14 +- app/models/live_assessments/result.rb | 4 +- app/models/lti/line_item.rb | 10 +- app/models/lti/resource_link.rb | 2 +- app/models/lti/result.rb | 2 +- app/models/lti/tool_configuration.rb | 6 +- app/models/lti/tool_proxy.rb | 20 +- app/models/many_root_accounts.rb | 2 +- .../master_courses/child_content_tag.rb | 2 +- .../master_courses/child_subscription.rb | 42 +- .../master_courses/collection_restrictor.rb | 20 +- .../master_courses/master_content_tag.rb | 38 +- app/models/master_courses/master_migration.rb | 98 +-- app/models/master_courses/master_template.rb | 98 +-- app/models/master_courses/migration_result.rb | 2 +- app/models/master_courses/restrictor.rb | 60 +- app/models/master_courses/tag_helper.rb | 10 +- app/models/media_object.rb | 70 +-- app/models/media_track.rb | 6 +- app/models/message.rb | 92 +-- app/models/microsoft_sync/group.rb | 2 +- app/models/microsoft_sync/user_mapping.rb | 6 +- .../moderated_grading/provisional_grade.rb | 24 +- app/models/notification.rb | 26 +- app/models/notification_endpoint.rb | 12 +- app/models/notification_failure_processor.rb | 4 +- app/models/notification_preloader.rb | 4 +- app/models/observer_alert_threshold.rb | 26 +- app/models/observer_pairing_code.rb | 2 +- app/models/originality_report.rb | 8 +- app/models/outcome_import.rb | 18 +- app/models/outcome_proficiency.rb | 16 +- app/models/outcome_proficiency_rating.rb | 12 +- app/models/pace_plan.rb | 8 +- app/models/pace_plan_module_item.rb | 2 +- app/models/page_comment.rb | 2 +- app/models/page_view.rb | 42 +- app/models/parallel_importer.rb | 10 +- app/models/planner_override.rb | 16 +- app/models/plugin_setting.rb | 16 +- app/models/polling/poll.rb | 4 +- app/models/polling/poll_session.rb | 14 +- app/models/polling/poll_submission.rb | 12 +- app/models/progress.rb | 6 +- app/models/pseudonym.rb | 118 ++-- app/models/pseudonym_session.rb | 8 +- app/models/purgatory.rb | 2 +- app/models/quizzes/quiz.rb | 326 +++++----- app/models/quizzes/quiz_extension.rb | 2 +- app/models/quizzes/quiz_group.rb | 26 +- app/models/quizzes/quiz_participant.rb | 2 +- app/models/quizzes/quiz_question.rb | 50 +- .../answer_serializers/answer_serializer.rb | 8 +- app/models/quizzes/quiz_question/base.rb | 4 +- .../quiz_question/file_upload_question.rb | 4 +- app/models/quizzes/quiz_statistics.rb | 8 +- .../quizzes/quiz_statistics/item_analysis.rb | 2 +- app/models/quizzes/quiz_submission.rb | 210 +++---- app/models/quizzes/quiz_submission_event.rb | 4 +- app/models/report_snapshot.rb | 10 +- app/models/role.rb | 68 +-- app/models/role_override.rb | 16 +- app/models/rubric.rb | 80 +-- app/models/rubric_assessment.rb | 100 +-- app/models/rubric_association.rb | 88 +-- app/models/session_persistence_token.rb | 12 +- app/models/shared_brand_config.rb | 2 +- app/models/sis_batch.rb | 178 +++--- app/models/sis_batch_error.rb | 2 +- app/models/sis_pseudonym.rb | 2 +- app/models/stream_item.rb | 32 +- app/models/stream_item_instance.rb | 2 +- app/models/student_enrollment.rb | 4 +- app/models/submission.rb | 482 +++++++-------- app/models/submission_comment.rb | 68 +-- app/models/submission_draft.rb | 28 +- app/models/terms_of_service.rb | 14 +- app/models/terms_of_service_content.rb | 4 +- app/models/thumbnail.rb | 4 +- app/models/user.rb | 404 ++++++------- app/models/user_learning_object_scopes.rb | 2 +- app/models/user_merge_data.rb | 8 +- app/models/user_note.rb | 14 +- app/models/user_observation_link.rb | 12 +- app/models/user_preference_value.rb | 34 +- app/models/user_profile.rb | 2 +- app/models/user_service.rb | 20 +- app/models/web_conference.rb | 68 +-- app/models/web_zip_export.rb | 2 +- app/models/wiki.rb | 68 +-- app/models/wiki_page.rb | 110 ++-- app/observers/stream_item_cache.rb | 6 +- config/application.rb | 2 +- config/initializers/active_record.rb | 64 +- config/initializers/active_support.rb | 2 +- config/initializers/folio.rb | 6 +- config/initializers/marginalia.rb | 2 +- config/initializers/switchman.rb | 4 +- config/initializers/time.rb | 4 +- db/migrate/20101210192618_init_canvas_db.rb | 4 +- ...d_submissions_for_assignment_visibility.rb | 16 +- ..._null_constraint_to_scores_course_score.rb | 6 +- ...te_assignment_student_visibilities_view.rb | 4 +- ...dent_visibilities_view_submissions_join.rb | 4 +- ...0523134906_update_asv_enrollment_filter.rb | 4 +- ...613202631_improve_asv_group_performance.rb | 4 +- ...mize_assignment_student_visibility_view.rb | 4 +- ...9_optimize_quiz_student_visibility_view.rb | 4 +- ..._tool_to_anonymous_or_moderation_events.rb | 4 +- ...0001917_update_asv_enrollment_filter_v2.rb | 4 +- .../lib/active_record/acts/list.rb | 2 +- .../lib/adheres_to_policy/cache.rb | 4 +- .../instance_methods_spec.rb | 4 +- gems/attachment_fu/lib/attachment_fu.rb | 36 +- .../backends/file_system_backend.rb | 4 +- .../lib/attachment_fu/backends/s3_backend.rb | 6 +- .../simple_bookmarker.rb | 2 +- .../lib/broadcast_policy/instance_methods.rb | 4 +- .../broadcast_policy/notification_policy.rb | 8 +- .../lib/broadcast_policy/policy_list.rb | 10 +- gems/canvas_cache/lib/canvas_cache/redis.rb | 6 +- gems/canvas_errors/lib/canvas_errors.rb | 2 +- gems/canvas_ext/lib/canvas_ext/array.rb | 4 +- gems/canvas_http/lib/canvas_http.rb | 4 +- .../lib/canvas_panda_pub/async_worker.rb | 4 +- .../canvas_partman/concerns/partitioned.rb | 2 +- .../lib/canvas_partman/partition_manager.rb | 2 +- .../canvas_partman/partition_manager/by_id.rb | 4 +- gems/canvas_partman/spec/fixtures/animal.rb | 2 +- gems/canvas_partman/spec/fixtures/trail.rb | 2 +- .../spec/fixtures/week_event.rb | 6 +- gems/canvas_partman/spec/fixtures/zoo.rb | 2 +- .../spec/support/schema_helper.rb | 2 +- .../canvas_quiz_statistics/analyzers/base.rb | 2 +- .../analyzers/base/dsl.rb | 10 +- .../lib/canvas_sanitize/canvas_sanitize.rb | 6 +- gems/canvas_security/lib/canvas_security.rb | 4 +- .../lib/lucky_sneaks/acts_as_url.rb | 8 +- .../lib/lucky_sneaks/string_extensions.rb | 2 +- gems/canvas_time/lib/canvas_time.rb | 2 +- gems/canvas_unzip/lib/canvas_unzip.rb | 4 +- gems/diigo/lib/diigo/connection.rb | 2 +- gems/event_stream/lib/event_stream/index.rb | 4 +- .../index_strategy/active_record_spec.rb | 8 +- .../index_strategy/cassandra_spec.rb | 2 +- .../spec/event_stream/stream_spec.rb | 18 +- .../incoming_message_processor.rb | 14 +- gems/json_token/lib/json_token.rb | 4 +- .../lib/live_events/async_worker.rb | 4 +- .../lib/lti_advantage/messages/jwt_message.rb | 4 +- .../lib/lti_outbound/lti_model.rb | 4 +- .../lib/academic_benchmark.rb | 38 +- .../account_reports/lib/account_reports.rb | 2 +- .../lib/account_reports/report_helper.rb | 4 +- .../lib/account_reports/sis_exporter.rb | 4 +- .../lib/qti/assessment_item_converter.rb | 4 +- .../lib/respondus_soap_endpoint/middleware.rb | 6 +- .../urn_RespondusAPIServant.rb | 6 +- .../integration/respondus_endpoint_spec.rb | 2 +- .../simply_versioned/lib/simply_versioned.rb | 30 +- .../lib/simply_versioned/version.rb | 10 +- .../lib/request_context/generator.rb | 20 +- gems/tatl_tael/lib/tatl_tael/linters.rb | 2 +- gems/utf8_cleaner/lib/utf8_cleaner.rb | 6 +- gems/workflow/lib/workflow.rb | 2 +- lib/account_services.rb | 2 +- lib/active_record/cache_register.rb | 38 +- lib/active_support/cache_register.rb | 2 +- lib/anonymity.rb | 2 +- lib/api.rb | 6 +- lib/api/errors.rb | 2 +- lib/api/html/content.rb | 6 +- lib/api/v1/assignment.rb | 2 +- lib/api/v1/course.rb | 2 +- lib/api/v1/course_json.rb | 4 +- lib/api/v1/stream_item.rb | 2 +- lib/api_route_set.rb | 6 +- lib/assignment_override_applicator.rb | 18 +- lib/basic_lti/basic_outcomes.rb | 14 +- lib/basic_lti/quizzes_next_lti_response.rb | 4 +- lib/basic_lti/sourcedid.rb | 2 +- lib/brand_config_helpers.rb | 4 +- lib/canvadocs.rb | 2 +- lib/canvas/apm.rb | 24 +- lib/canvas/draft_state_validations.rb | 6 +- lib/canvas/errors/log_entry.rb | 2 +- lib/canvas/migration/archive.rb | 10 +- .../migration/external_content/migrator.rb | 14 +- lib/canvas/plugin.rb | 12 +- .../plugins/ticketing_system/custom_error.rb | 50 +- lib/canvas/security/login_registry.rb | 2 +- lib/cc/exporter/epub/exportable.rb | 2 +- lib/cc/exporter/web_zip/exportable.rb | 4 +- lib/cc/importer/standard/converter.rb | 2 +- lib/cc/resource.rb | 2 +- lib/content_notices.rb | 2 +- lib/copy_authorized_links.rb | 16 +- lib/course_link_validator.rb | 68 +-- lib/csv_with_i18n.rb | 2 +- lib/cuty_capt.rb | 8 +- .../copy_built_in_roles_by_root_account.rb | 2 +- ...nit_new_grade_history_audit_log_indexes.rb | 2 +- .../migrate_messages_to_partitions.rb | 2 +- lib/dates_overridable.rb | 18 +- lib/differentiable_assignment.rb | 22 +- lib/due_date_cacher.rb | 4 +- lib/feature.rb | 6 +- lib/feature_flags.rb | 24 +- lib/feature_flags/loader.rb | 4 +- lib/file_splitter.rb | 2 +- lib/gradebook_importer.rb | 4 +- lib/has_content_tags.rb | 22 +- lib/inst_fs.rb | 4 +- lib/learning_outcome_context.rb | 2 +- lib/lti/app_launch_collator.rb | 2 +- lib/lti/variable_expander.rb | 8 +- lib/message_bus.rb | 16 +- lib/message_bus/async_producer.rb | 4 +- lib/message_bus/ca_cert.rb | 2 +- lib/message_bus/message_id.rb | 8 +- lib/message_bus/namespace.rb | 2 +- lib/message_dispatcher.rb | 8 +- lib/messageable_user.rb | 4 +- lib/microsoft_sync/state_machine_job.rb | 8 +- lib/mutable.rb | 8 +- lib/open_object.rb | 8 +- lib/plannable.rb | 16 +- lib/request_error.rb | 4 +- lib/schemas/base.rb | 2 +- lib/score_statistics_generator.rb | 4 +- lib/search_term_helper.rb | 2 +- lib/send_to_stream.rb | 12 +- lib/sentry_proxy.rb | 2 +- lib/sis/account_importer.rb | 2 +- lib/sis/csv/import_refactored.rb | 2 +- lib/sorts_assignments.rb | 2 +- lib/ssl_common.rb | 10 +- lib/sticky_sis_fields.rb | 4 +- lib/submission_list.rb | 28 +- lib/submittable.rb | 66 +- lib/unzip_attachment.rb | 24 +- lib/visibility_plucking_helper.rb | 2 +- lib/zip_extractor.rb | 6 +- spec/apis/api_spec_helper.rb | 2 +- spec/apis/general_api_spec.rb | 2 +- spec/apis/v1/discussion_topics_api_spec.rb | 4 +- spec/apis/v1/pages_api_spec.rb | 4 +- spec/apis/v1/submissions_api_spec.rb | 4 +- .../api/provider_states_for_consumer.rb | 2 +- .../oauth_provider_states.rb | 2 +- .../ims/names_and_roles_controller_spec.rb | 2 +- spec/lib/canvas/apm_common.rb | 2 +- spec/messages/messages_helper.rb | 2 +- spec/models/assignment_spec.rb | 2 +- .../da_assignment.rb | 2 +- .../da_course_modules_module.rb | 20 +- .../da_discussion.rb | 2 +- .../da_homework_assignments_module.rb | 38 +- .../da_homework_discussions_module.rb | 38 +- .../da_homework_quizzes_module.rb | 38 +- .../differentiated_assignments/da_quiz.rb | 2 +- .../da_users_module.rb | 20 +- .../da_wrappable.rb | 8 +- .../test_setup/selenium_extensions.rb | 2 +- spec/spec_helper.rb | 4 +- 410 files changed, 5567 insertions(+), 5593 deletions(-) diff --git a/.rubocop.common.yml b/.rubocop.common.yml index 20f9613283bdd..b455187b67b7e 100644 --- a/.rubocop.common.yml +++ b/.rubocop.common.yml @@ -373,6 +373,8 @@ Style/RedundantRegexpEscape: Severity: error Style/RedundantReturn: Severity: error +Style/RedundantSelf: + Severity: error Style/RedundantSelfAssignment: Severity: error Style/RedundantSelfAssignmentBranch: @@ -485,8 +487,6 @@ Style/NumericLiterals: # TODO: autocorrect Enabled: false Style/ParallelAssignment: # TODO: autocorrect (with probable exceptions) Enabled: false -Style/RedundantSelf: # TODO: autocorrect - Enabled: false Style/RescueModifier: # TODO Severity: warning AutoCorrect: false diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index b8e0a1925dbaf..876f8185d3870 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -574,11 +574,11 @@ def named_context_url(context, name, *opts) # rubocop:enable Style/RescueModifier opts[-1][:only_path] = true unless name.end_with?("_path") end - self.send name, *opts + send name, *opts end def self.promote_view_path(path) - self.view_paths = self.view_paths.to_ary.reject { |p| p.to_s == path } + self.view_paths = view_paths.to_ary.reject { |p| p.to_s == path } prepend_view_path(path) end @@ -976,7 +976,7 @@ def get_context(include_deleted: false) end @context_membership = @context_enrollment check_for_readonly_enrollment_state - elsif params[:account_id] || (self.is_a?(AccountsController) && (params[:account_id] = params[:id])) + elsif params[:account_id] || (is_a?(AccountsController) && (params[:account_id] = params[:id])) @context = api_find(Account.active, params[:account_id]) params[:context_id] = @context.id params[:context_type] = "Account" @@ -989,13 +989,13 @@ def get_context(include_deleted: false) params[:context_type] = "Group" @context_enrollment = @context.group_memberships.where(user_id: @current_user).first if @context && @current_user @context_membership = @context_enrollment - elsif params[:user_id] || (self.is_a?(UsersController) && (params[:user_id] = params[:id])) + elsif params[:user_id] || (is_a?(UsersController) && (params[:user_id] = params[:id])) scope = include_deleted ? User : User.active @context = api_find(scope, params[:user_id]) params[:context_id] = params[:user_id] params[:context_type] = "User" @context_membership = @context if @context == @current_user - elsif params[:course_section_id] || (self.is_a?(SectionsController) && (params[:course_section_id] = params[:id])) + elsif params[:course_section_id] || (is_a?(SectionsController) && (params[:course_section_id] = params[:id])) params[:context_id] = params[:course_section_id] params[:context_type] = "CourseSection" @context = api_find(CourseSection, params[:course_section_id]) diff --git a/app/controllers/assignments_controller.rb b/app/controllers/assignments_controller.rb index 51b515287cf19..91e51a4708b70 100644 --- a/app/controllers/assignments_controller.rb +++ b/app/controllers/assignments_controller.rb @@ -719,7 +719,7 @@ def edit hash[:CONTEXT_ACTION_SOURCE] = :assignments hash[:DUE_DATE_REQUIRED_FOR_ACCOUNT] = AssignmentUtil.due_date_required_for_account?(@context) hash[:MAX_NAME_LENGTH_REQUIRED_FOR_ACCOUNT] = AssignmentUtil.name_length_required_for_account?(@context) - hash[:MAX_NAME_LENGTH] = self.try(:context).try(:account).try(:sis_assignment_name_length_input).try(:[], :value).to_i + hash[:MAX_NAME_LENGTH] = try(:context).try(:account).try(:sis_assignment_name_length_input).try(:[], :value).to_i selected_tool = @assignment.tool_settings_tool hash[:SELECTED_CONFIG_TOOL_ID] = selected_tool ? selected_tool.id : nil diff --git a/app/controllers/context_modules_api_controller.rb b/app/controllers/context_modules_api_controller.rb index 03aca6b2ac992..e3f41a20040fd 100644 --- a/app/controllers/context_modules_api_controller.rb +++ b/app/controllers/context_modules_api_controller.rb @@ -177,7 +177,7 @@ def index if includes.include?('items') if @context.user_has_been_observer?(@student || @current_user) - opts[:observed_student_ids] = ObserverEnrollment.observed_student_ids(self.context, (@student || @current_user)) + opts[:observed_student_ids] = ObserverEnrollment.observed_student_ids(context, (@student || @current_user)) end end diff --git a/app/controllers/gradebooks_controller.rb b/app/controllers/gradebooks_controller.rb index 652e28d4a4a8c..811e9a36abaa9 100644 --- a/app/controllers/gradebooks_controller.rb +++ b/app/controllers/gradebooks_controller.rb @@ -287,7 +287,7 @@ def show_learning_mastery private :show_learning_mastery def post_grades_ltis - @post_grades_ltis ||= self.external_tools.map { |tool| external_tool_detail(tool) } + @post_grades_ltis ||= external_tools.map { |tool| external_tool_detail(tool) } end def external_tool_detail(tool) diff --git a/app/controllers/lti/concerns/sessionless_launches.rb b/app/controllers/lti/concerns/sessionless_launches.rb index 6f6580585f74d..a1aba2b003aa8 100644 --- a/app/controllers/lti/concerns/sessionless_launches.rb +++ b/app/controllers/lti/concerns/sessionless_launches.rb @@ -130,7 +130,7 @@ def assignment_launch_link(assignment, session_token) def course_or_account_launch_link(context, tool, session_token, launch_url) context_type = context.class.to_s.downcase - self.send( + send( "#{context_type}_external_tool_url", context.id, id: tool.id, diff --git a/app/controllers/media_objects_controller.rb b/app/controllers/media_objects_controller.rb index cbf9d45c0e1c8..d6e5acc32c539 100644 --- a/app/controllers/media_objects_controller.rb +++ b/app/controllers/media_objects_controller.rb @@ -185,7 +185,7 @@ def update_media_object ) end - self.extend TextHelper + extend TextHelper @media_object.user_entered_title = CanvasTextHelper.truncate_text(params[:user_entered_title], max_length: 255) @media_object.save! @@ -198,7 +198,7 @@ def create_media_object if authorized_action(@context, @current_user, :read) if params[:id] && params[:type] && @context.respond_to?(:media_objects) - self.extend TextHelper + extend TextHelper # The MediaObject will be created on the current shard, # not the @context's shard. diff --git a/app/controllers/outcome_results_controller.rb b/app/controllers/outcome_results_controller.rb index 19dc55dab1f48..314465b1e8618 100644 --- a/app/controllers/outcome_results_controller.rb +++ b/app/controllers/outcome_results_controller.rb @@ -427,7 +427,7 @@ def linked_include_collections linked = {} includes = Api.value_to_array(params[:include]) includes.uniq.each do |include_name| - linked[include_name] = self.send(include_method_name(include_name)) + linked[include_name] = send(include_method_name(include_name)) end linked end @@ -520,7 +520,7 @@ def verify_include_parameter when 'users' reject! "can't include users unless aggregate is not set" if params[:aggregate].present? else - reject! "invalid include: #{include_name}" unless self.respond_to? include_method_name(include_name), :include_private + reject! "invalid include: #{include_name}" unless respond_to? include_method_name(include_name), :include_private end end true diff --git a/app/controllers/release_notes_controller.rb b/app/controllers/release_notes_controller.rb index c2c99ee789ccc..a0c504c5e3136 100644 --- a/app/controllers/release_notes_controller.rb +++ b/app/controllers/release_notes_controller.rb @@ -169,8 +169,8 @@ def include_langs? # For specs only def clear_ivars - self.instance_variables.each do |ivar| - self.instance_variable_set(ivar, nil) + instance_variables.each do |ivar| + instance_variable_set(ivar, nil) end end end diff --git a/app/controllers/user_notes_controller.rb b/app/controllers/user_notes_controller.rb index 5a6a3c8ac94c1..07a24ad01b87e 100644 --- a/app/controllers/user_notes_controller.rb +++ b/app/controllers/user_notes_controller.rb @@ -67,7 +67,7 @@ def create # We want notes to be an html field, but we're only using a plaintext box for now. That's why we're # doing the trip to html now, instead of on the way out. This should be removed once the user notes # entry form is replaced with the rich text editor. - self.extend TextHelper + extend TextHelper user_note_params[:note] = format_message(user_note_params[:note]).first if user_note_params[:note] user_note_params[:root_account_id] = @domain_root_account.id @user_note = user.user_notes.new(user_note_params) diff --git a/app/graphql/graphql_helpers.rb b/app/graphql/graphql_helpers.rb index 2ff621a3784b4..4dd1708324144 100644 --- a/app/graphql/graphql_helpers.rb +++ b/app/graphql/graphql_helpers.rb @@ -26,7 +26,7 @@ module GraphQLHelpers # will get a standard canvas id def self.relay_or_legacy_id_prepare_func(expected_type) proc do |relay_or_legacy_id| - self.parse_relay_or_legacy_id(relay_or_legacy_id, expected_type) + parse_relay_or_legacy_id(relay_or_legacy_id, expected_type) rescue InvalidIDError => e GraphQL::ExecutionError.new(e.message) end @@ -35,7 +35,7 @@ def self.relay_or_legacy_id_prepare_func(expected_type) def self.relay_or_legacy_ids_prepare_func(expected_type) proc do |relay_or_legacy_ids| relay_or_legacy_ids.map do |relay_or_legacy_id| - self.parse_relay_or_legacy_id(relay_or_legacy_id, expected_type) + parse_relay_or_legacy_id(relay_or_legacy_id, expected_type) end rescue InvalidIDError => e GraphQL::ExecutionError.new(e.message) diff --git a/app/graphql/graphql_postgres_timeout.rb b/app/graphql/graphql_postgres_timeout.rb index 0a7e78654cebf..501335aa1ded3 100644 --- a/app/graphql/graphql_postgres_timeout.rb +++ b/app/graphql/graphql_postgres_timeout.rb @@ -24,7 +24,7 @@ class << self end def self.wrap(query) - if self.do_not_wrap + if do_not_wrap yield else ActiveRecord::Base.transaction do diff --git a/app/graphql/mutations/add_conversation_message.rb b/app/graphql/mutations/add_conversation_message.rb index fa06964ae1876..f8a59e69d661c 100644 --- a/app/graphql/mutations/add_conversation_message.rb +++ b/app/graphql/mutations/add_conversation_message.rb @@ -47,7 +47,7 @@ def resolve(input:) message_ids: input[:included_messages], body: input[:body], attachment_ids: input[:attachment_ids], - domain_root_account_id: self.context[:domain_root_account].id, + domain_root_account_id: context[:domain_root_account].id, media_comment_id: input[:media_comment_id], media_comment_type: input[:media_comment_type], user_note: input[:user_note] diff --git a/app/graphql/mutations/update_assignment.rb b/app/graphql/mutations/update_assignment.rb index 6d5a5dce59fbf..fde29d1d91b47 100644 --- a/app/graphql/mutations/update_assignment.rb +++ b/app/graphql/mutations/update_assignment.rb @@ -68,7 +68,7 @@ def resolve(input:) module_ids = prepare_module_ids!(input_hash) # make sure to do other required updates - self.send(other_update_on_assignment) if other_update_on_assignment + send(other_update_on_assignment) if other_update_on_assignment # ensure the assignment is part of all required modules ensure_modules(module_ids) if module_ids diff --git a/app/graphql/types/communication_channel_type.rb b/app/graphql/types/communication_channel_type.rb index 367f03209f0f7..c13e9a2f1e4e8 100644 --- a/app/graphql/types/communication_channel_type.rb +++ b/app/graphql/types/communication_channel_type.rb @@ -36,7 +36,7 @@ class CommunicationChannelType < ApplicationObjectType argument :context_type, NotificationPreferencesContextType, required: false end def notification_policies(context_type: nil) - NotificationPolicy.find_all_for(self.object, context_type: context_type) + NotificationPolicy.find_all_for(object, context_type: context_type) end field :notification_policy_overrides, [NotificationPolicyType], null: true do diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index a4503eef9f1a3..79caf943b9b7a 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -111,7 +111,7 @@ def context_url(context, *opts) nil end opts[-1][:only_path] = true unless opts[-1][:only_path] == false - res = self.send name, *opts + res = send name, *opts elsif opts[0].is_a? Hash opts = opts[0] begin @@ -121,7 +121,7 @@ def context_url(context, *opts) end opts[:only_path] = true opts["#{context_name}_id"] = context.id - res = self.url_for opts + res = url_for opts else res = context_name.to_s + opts.to_json.to_s end diff --git a/app/helpers/attachment_helper.rb b/app/helpers/attachment_helper.rb index b8e43d8836e9a..93a8bb7d98875 100644 --- a/app/helpers/attachment_helper.rb +++ b/app/helpers/attachment_helper.rb @@ -42,8 +42,8 @@ def doc_preview_attributes(attachment, attrs = {}) attrs[:mimetype] = attachment.mimetype context_name = url_helper_context_from_object(attachment.context) url_helper = "#{context_name}_file_inline_view_url" - if self.respond_to?(url_helper) - attrs[:attachment_view_inline_ping_url] = self.send(url_helper, attachment.context, attachment.id, { :verifier => params[:verifier] }) + if respond_to?(url_helper) + attrs[:attachment_view_inline_ping_url] = send(url_helper, attachment.context, attachment.id, { :verifier => params[:verifier] }) end if attachment.pending_upload? || attachment.processing? attrs[:attachment_preview_processing] = true diff --git a/app/helpers/datadog_rum_helper.rb b/app/helpers/datadog_rum_helper.rb index d6e23d94dc0c3..578530a7aa431 100644 --- a/app/helpers/datadog_rum_helper.rb +++ b/app/helpers/datadog_rum_helper.rb @@ -64,7 +64,7 @@ def enabled? end def randomly_include? - self.random <= sample_rate + random <= sample_rate end def sample_rate diff --git a/app/helpers/search_helper.rb b/app/helpers/search_helper.rb index ce192a3c6c1ae..ccb2e933ce703 100644 --- a/app/helpers/search_helper.rb +++ b/app/helpers/search_helper.rb @@ -321,7 +321,7 @@ def validate(bookmark) end def self.wrap(collection) - BookmarkedCollection.build(self.new(collection)) do |pager| + BookmarkedCollection.build(new(collection)) do |pager| page_start = pager.current_bookmark ? pager.current_bookmark + 1 : 0 page_end = page_start + pager.per_page pager.replace collection[page_start, page_end] diff --git a/app/middleware/request_throttle.rb b/app/middleware/request_throttle.rb index f40d795f7f33c..cd9f7722fc473 100644 --- a/app/middleware/request_throttle.rb +++ b/app/middleware/request_throttle.rb @@ -312,7 +312,7 @@ def get_up_front_cost_for_path(path) self.class.up_front_cost_by_path_regex.each do |regex, cost| return cost if regex&.match?(path) end - self.up_front_cost # otherwise use the default + up_front_cost # otherwise use the default end # This method does an initial increment by the up_front_cost, loading the @@ -347,7 +347,7 @@ def increment(amount, reserve_cost = 0, current_time = Time.now) end current_time = current_time.to_f - Rails.logger.debug("request throttling increment: #{([amount, reserve_cost, current_time] + self.as_json.to_a).to_json}") + Rails.logger.debug("request throttling increment: #{([amount, reserve_cost, current_time] + as_json.to_a).to_json}") redis = self.redis count, last_touched = LeakyBucket.lua.run(:increment_bucket, [cache_key], [amount + reserve_cost, current_time, outflow, maximum], redis) self.count = count.to_f diff --git a/app/models/access_token.rb b/app/models/access_token.rb index fe8516cff9dd8..fca89339be70c 100644 --- a/app/models/access_token.rb +++ b/app/models/access_token.rb @@ -79,7 +79,7 @@ def self.authenticate(token_string, token_key = :crypted_token) # hash the user supplied token with all of our known keys # attempt to find a token that matches one of the hashes hashed_tokens = all_hashed_tokens(token_string) - token = self.not_deleted.where(token_key => hashed_tokens).first + token = not_deleted.where(token_key => hashed_tokens).first if token && token.send(token_key) != hashed_tokens.first # we found the token but, its hashed using an old key. save the updated hash token.send("#{token_key}=", hashed_tokens.first) @@ -90,7 +90,7 @@ def self.authenticate(token_string, token_key = :crypted_token) end def self.authenticate_refresh_token(token_string) - self.authenticate(token_string, :crypted_refresh_token) + authenticate(token_string, :crypted_refresh_token) end def self.hashed_token(token) @@ -136,7 +136,7 @@ def record_last_used_threshold def used! if !last_used_at || last_used_at < record_last_used_threshold.seconds.ago self.last_used_at = Time.now.utc - self.save + save end end @@ -159,7 +159,7 @@ def clear_full_token! end def generate_token(overwrite = false) - if overwrite || !self.crypted_token + if overwrite || !crypted_token self.token = CanvasSlug.generate(nil, TOKEN_SIZE) self.expires_at = Time.now.utc + 1.hour if developer_key&.auto_expire_tokens diff --git a/app/models/account.rb b/app/models/account.rb index 215c9327b2fea..f1b269c9274a7 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -216,7 +216,7 @@ def resolved_outcome_proficiency outcome_proficiency elsif parent_account parent_account.resolved_outcome_proficiency - elsif self.feature_enabled?(:account_level_mastery_scales) + elsif feature_enabled?(:account_level_mastery_scales) OutcomeProficiency.find_or_create_default!(self) end end @@ -229,7 +229,7 @@ def resolved_outcome_calculation_method outcome_calculation_method elsif parent_account parent_account.resolved_outcome_calculation_method - elsif self.feature_enabled?(:account_level_mastery_scales) + elsif feature_enabled?(:account_level_mastery_scales) OutcomeCalculationMethod.find_or_create_default!(self) end end @@ -366,7 +366,7 @@ def settings=(hash) hash.each do |key, val| key = key.to_sym if account_settings_options && (opts = account_settings_options[key]) - if (opts[:root_only] && !self.root_account?) || (opts[:condition] && !self.send("#{opts[:condition]}?".to_sym)) + if (opts[:root_only] && !root_account?) || (opts[:condition] && !send("#{opts[:condition]}?".to_sym)) settings.delete key elsif opts[:hash] new_hash = {} @@ -460,8 +460,8 @@ def enable_as_k5_account? end def enable_as_k5_account! - self.settings[:enable_as_k5_account] = { value: true } - self.save! + settings[:enable_as_k5_account] = { value: true } + save! end def open_registration? @@ -534,7 +534,7 @@ def enable_sis_imports end def ensure_defaults - self.name&.delete!("\r") + name&.delete!("\r") self.uuid ||= CanvasSlug.generate_securish_uuid if has_attribute?(:uuid) self.lti_guid ||= "#{self.uuid}:#{INSTANCE_GUID_SUFFIX}" if has_attribute?(:lti_guid) self.root_account_id ||= parent_account.root_account_id if parent_account && !parent_account.root_account? @@ -549,20 +549,20 @@ def ensure_defaults def verify_unique_sis_source_id return true unless has_attribute?(:sis_source_id) - return true unless self.sis_source_id + return true unless sis_source_id return true if !root_account_id_changed? && !sis_source_id_changed? - if self.root_account? - self.errors.add(:sis_source_id, t('#account.root_account_cant_have_sis_id', "SIS IDs cannot be set on root accounts")) + if root_account? + errors.add(:sis_source_id, t('#account.root_account_cant_have_sis_id', "SIS IDs cannot be set on root accounts")) throw :abort end - scope = root_account.all_accounts.where(sis_source_id: self.sis_source_id) - scope = scope.where("id<>?", self) unless self.new_record? + scope = root_account.all_accounts.where(sis_source_id: sis_source_id) + scope = scope.where("id<>?", self) unless new_record? return true unless scope.exists? - self.errors.add(:sis_source_id, t('#account.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", :sis_id => self.sis_source_id)) + errors.add(:sis_source_id, t('#account.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", :sis_id => sis_source_id)) throw :abort end @@ -582,13 +582,13 @@ def check_downstream_caches return if ActiveRecord::Base.in_migration keys_to_clear = [] - keys_to_clear << :account_chain if self.saved_change_to_parent_account_id? || self.saved_change_to_root_account_id? - if self.saved_change_to_brand_config_md5? || (@old_settings && @old_settings[:sub_account_includes] != settings[:sub_account_includes]) + keys_to_clear << :account_chain if saved_change_to_parent_account_id? || saved_change_to_root_account_id? + if saved_change_to_brand_config_md5? || (@old_settings && @old_settings[:sub_account_includes] != settings[:sub_account_includes]) keys_to_clear << :brand_config end - keys_to_clear << :default_locale if self.saved_change_to_default_locale? + keys_to_clear << :default_locale if saved_change_to_default_locale? if keys_to_clear.any? - self.shard.activate do + shard.activate do self.class.connection.after_transaction_commit do delay_if_production(singleton: "Account#clear_downstream_caches/#{global_id}") .clear_downstream_caches(*keys_to_clear, xlog_location: self.class.current_xlog_location) @@ -598,7 +598,7 @@ def check_downstream_caches end def clear_downstream_caches(*key_types, xlog_location: nil, is_retry: false) - self.shard.activate do + shard.activate do if xlog_location timeout = Setting.get("account_cache_clear_replication_timeout", "60").to_i.seconds unless self.class.wait_for_replication(start: xlog_location, timeout: timeout) @@ -609,17 +609,17 @@ def clear_downstream_caches(*key_types, xlog_location: nil, is_retry: false) end end - Account.clear_cache_keys([self.id] + Account.sub_account_ids_recursive(self.id), *key_types) + Account.clear_cache_keys([id] + Account.sub_account_ids_recursive(id), *key_types) end end def equella_settings - endpoint = self.settings[:equella_endpoint] || self.equella_endpoint + endpoint = settings[:equella_endpoint] || equella_endpoint if !endpoint.blank? OpenObject.new({ :endpoint => endpoint, - :default_action => self.settings[:equella_action] || 'selectOrAdd', - :teaser => self.settings[:equella_teaser] + :default_action => settings[:equella_action] || 'selectOrAdd', + :teaser => settings[:equella_teaser] }) else nil @@ -627,7 +627,7 @@ def equella_settings end def settings - result = self.read_attribute(:settings) + result = read_attribute(:settings) if result @old_settings ||= result.dup return result @@ -642,7 +642,7 @@ def domain(current_host = nil) end def self.find_by_domain(domain) - self.default if HostUrl.default_host == domain + default if HostUrl.default_host == domain end def root_account? @@ -669,24 +669,24 @@ def resolved_root_account_id def sub_accounts_as_options(indent = 0, preloaded_accounts = nil) unless preloaded_accounts preloaded_accounts = {} - self.root_account.all_accounts.active.each do |account| + root_account.all_accounts.active.each do |account| (preloaded_accounts[account.parent_account_id] ||= []) << account end end - res = [[("  " * indent).html_safe + self.name, self.id]] - preloaded_accounts[self.id]&.each do |account| + res = [[("  " * indent).html_safe + name, id]] + preloaded_accounts[id]&.each do |account| res += account.sub_accounts_as_options(indent + 1, preloaded_accounts) end res end def users_visible_to(user) - self.grants_right?(user, :read) ? self.all_users : self.all_users.none + grants_right?(user, :read) ? all_users : all_users.none end def users_name_like(query = "") @cached_users_name_like ||= {} - @cached_users_name_like[query] ||= self.fast_all_users.name_like(query) + @cached_users_name_like[query] ||= fast_all_users.name_like(query) end def associated_courses(opts = {}) @@ -725,7 +725,7 @@ def fast_course_base(opts = {}) def fast_all_courses(opts = {}) @cached_fast_all_courses ||= {} - @cached_fast_all_courses[opts] ||= self.fast_course_base(opts) + @cached_fast_all_courses[opts] ||= fast_course_base(opts) end def all_users(limit = 250) @@ -735,7 +735,7 @@ def all_users(limit = 250) def fast_all_users(limit = nil) @cached_fast_all_users ||= {} - @cached_fast_all_users[limit] ||= self.all_users(limit).active.select("users.id, users.updated_at, users.name, users.sortable_name").order_by_sortable_name + @cached_fast_all_users[limit] ||= all_users(limit).active.select("users.id, users.updated_at, users.name, users.sortable_name").order_by_sortable_name end def users_not_in_groups(groups, opts = {}) @@ -750,7 +750,7 @@ def users_not_in_groups(groups, opts = {}) def courses_name_like(query = "", opts = {}) opts[:limit] ||= 200 @cached_courses_name_like ||= {} - @cached_courses_name_like[[query, opts]] ||= self.fast_course_base(opts) { |q| q.name_like(query) } + @cached_courses_name_like[[query, opts]] ||= fast_course_base(opts) { |q| q.name_like(query) } end def self_enrollment_course_for(code) @@ -784,11 +784,11 @@ def self.invalidate_cache(id) def setup_cache_invalidation @invalidations = [] - unless self.new_record? - invalidate_all = self.parent_account_id_changed? + unless new_record? + invalidate_all = parent_account_id_changed? # apparently, the try_rescues are because these columns don't exist on old migrations - @invalidations += ['default_storage_quota', 'current_quota'] if invalidate_all || self.try_rescue(:default_storage_quota_changed?) - @invalidations << 'default_group_storage_quota' if invalidate_all || self.try_rescue(:default_group_storage_quota_changed?) + @invalidations += ['default_storage_quota', 'current_quota'] if invalidate_all || try_rescue(:default_storage_quota_changed?) + @invalidations << 'default_group_storage_quota' if invalidate_all || try_rescue(:default_group_storage_quota_changed?) end end @@ -806,7 +806,7 @@ def invalidate_caches_if_changed end @invalidations ||= [] - if self.saved_change_to_parent_account_id? + if saved_change_to_parent_account_id? @invalidations += Account.inheritable_settings # invalidate all of them elsif @old_settings Account.inheritable_settings.each do |key| @@ -819,7 +819,7 @@ def invalidate_caches_if_changed shard.activate do self.class.connection.after_transaction_commit do @invalidations.each do |key| - Rails.cache.delete([key, self.global_id].cache_key) + Rails.cache.delete([key, global_id].cache_key) end Account.delay_if_production(singleton: "Account.invalidate_inherited_caches_#{global_id}") .invalidate_inherited_caches(self, @invalidations) @@ -854,8 +854,8 @@ def quota return self.class.default_storage_quota if root_account? shard.activate do - Rails.cache.fetch(['current_quota', self.global_id].cache_key) do - self.parent_account.default_storage_quota + Rails.cache.fetch(['current_quota', global_id].cache_key) do + parent_account.default_storage_quota end end end @@ -865,7 +865,7 @@ def default_storage_quota return self.class.default_storage_quota if root_account? shard.activate do - @default_storage_quota ||= Rails.cache.fetch(['default_storage_quota', self.global_id].cache_key) do + @default_storage_quota ||= Rails.cache.fetch(['default_storage_quota', global_id].cache_key) do parent_account.default_storage_quota end end @@ -914,8 +914,8 @@ def default_group_storage_quota return Group.default_storage_quota if root_account? shard.activate do - Rails.cache.fetch(['default_group_storage_quota', self.global_id].cache_key) do - self.parent_account.default_group_storage_quota + Rails.cache.fetch(['default_group_storage_quota', global_id].cache_key) do + parent_account.default_group_storage_quota end end end @@ -923,7 +923,7 @@ def default_group_storage_quota def default_group_storage_quota=(val) val = val.to_i if (val == Group.default_storage_quota) || (val <= 0) || - (self.parent_account && self.parent_account.default_group_storage_quota == val) + (parent_account && parent_account.default_group_storage_quota == val) val = nil end write_attribute(:default_group_storage_quota, val) @@ -944,9 +944,9 @@ def turnitin_shared_secret=(secret) end def turnitin_shared_secret - return nil unless self.turnitin_salt && self.turnitin_crypted_secret + return nil unless turnitin_salt && turnitin_crypted_secret - Canvas::Security.decrypt_password(self.turnitin_crypted_secret, self.turnitin_salt, 'instructure_turnitin_secret_shared') + Canvas::Security.decrypt_password(turnitin_crypted_secret, turnitin_salt, 'instructure_turnitin_secret_shared') end def self.account_chain(starting_account_id) @@ -1051,9 +1051,9 @@ def account_chain_loop # this record hasn't been saved to the db yet, so if the the chain includes # this account, it won't point to the new parent yet, and should still be # valid - if self.parent_account.account_chain.include?(self) + if parent_account.account_chain.include?(self) errors.add(:parent_account_id, - "Setting account #{self.sis_source_id || self.id}'s parent to #{self.parent_account.sis_source_id || self.parent_account_id} would create a loop") + "Setting account #{sis_source_id || id}'s parent to #{parent_account.sis_source_id || self.parent_account_id} would create a loop") end end @@ -1126,11 +1126,11 @@ def self.sub_accounts_recursive_sql(parent_account_id) end def associated_accounts - self.account_chain + account_chain end def membership_for_user(user) - self.account_users.active.where(user_id: user).first if user + account_users.active.where(user_id: user).first if user end def available_custom_account_roles(include_inactive = false) @@ -1180,11 +1180,11 @@ def get_course_role_by_name(role_name) end def get_role_by_name(role_name) - if (role = Role.get_built_in_role(role_name, root_account_id: self.resolved_root_account_id)) + if (role = Role.get_built_in_role(role_name, root_account_id: resolved_root_account_id)) return role end - self.shard.activate do + shard.activate do role_scope = Role.not_deleted.where(:name => role_name) role_scope = if self.class.connection.adapter_name == 'PostgreSQL' role_scope.where("account_id = ? OR @@ -1195,9 +1195,9 @@ def get_role_by_name(role_name) SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t - )", self.id, self.id) + )", id, id) else - role_scope.where(:account_id => self.account_chain.map(&:id)) + role_scope.where(:account_id => account_chain.map(&:id)) end role_scope.first @@ -1210,17 +1210,17 @@ def get_role_by_id(role_id) end def valid_role?(role) - role && (role.built_in? || (self.id == role.account_id) || self.account_chain_ids.include?(role.account_id)) + role && (role.built_in? || (id == role.account_id) || account_chain_ids.include?(role.account_id)) end def login_handle_name_is_customized? - self.login_handle_name.present? + login_handle_name.present? end def customized_login_handle_name if login_handle_name_is_customized? - self.login_handle_name - elsif self.delegated_authentication? + login_handle_name + elsif delegated_authentication? AuthenticationProvider.default_delegated_login_handle_name end end @@ -1230,7 +1230,7 @@ def login_handle_name_with_inference end def self_and_all_sub_accounts - @self_and_all_sub_accounts ||= Account.where("root_account_id=? OR parent_account_id=?", self, self).pluck(:id).uniq + [self.id] + @self_and_all_sub_accounts ||= Account.where("root_account_id=? OR parent_account_id=?", self, self).pluck(:id).uniq + [id] end workflow do @@ -1243,7 +1243,7 @@ def account_users_for(user) shard.activate do all_site_admin_account_users_hash = MultiCache.fetch("all_site_admin_account_users3") do # this is a plain ruby hash to keep the cached portion as small as possible - self.account_users.active.each_with_object({}) { |au, result| + account_users.active.each_with_object({}) { |au, result| result[au.user_id] ||= [] result[au.user_id] << [au.id, au.role_id] } @@ -1263,7 +1263,7 @@ def account_users_for(user) end end else - @account_chain_ids ||= self.account_chain(:include_site_admin => true).filter_map { |a| a.active? ? a.id : nil } + @account_chain_ids ||= account_chain(:include_site_admin => true).filter_map { |a| a.active? ? a.id : nil } Shard.partition_by_shard(@account_chain_ids) do |account_chain_ids| if account_chain_ids == [Account.site_admin.id] Account.site_admin.account_users_for(user) @@ -1278,7 +1278,7 @@ def cached_account_users_for(user) return [] unless user @account_users_cache ||= {} - @account_users_cache[user.global_id] ||= if self.site_admin? + @account_users_cache[user.global_id] ||= if site_admin? account_users_for(user) # has own cache else Rails.cache.fetch_with_batched_keys(['account_users_for_user', user.cache_key(:account_users)].cache_key, @@ -1290,7 +1290,7 @@ def cached_account_users_for(user) # returns all active account users for this entire account tree def all_account_users_for(user) - raise "must be a root account" unless self.root_account? + raise "must be a root account" unless root_account? Shard.partition_by_shard(account_chain(include_site_admin: true).uniq) do |accounts| next unless user.associated_shards.include?(Shard.current) @@ -1310,45 +1310,45 @@ def cached_all_account_users_for(user) set_policy do RoleOverride.permissions.each do |permission, _details| - given { |user| self.cached_account_users_for(user).any? { |au| au.has_permission_to?(self, permission) } } + given { |user| cached_account_users_for(user).any? { |au| au.has_permission_to?(self, permission) } } can permission can :create_courses if permission == :manage_courses_add end - given { |user| !self.cached_account_users_for(user).empty? } + given { |user| !cached_account_users_for(user).empty? } can :read and can :read_as_admin and can :manage and can :update and can :delete and can :read_outcomes and can :read_terms - given { |user| self.root_account? && self.cached_all_account_users_for(user).any? } + given { |user| root_account? && cached_all_account_users_for(user).any? } can :read_terms given { |user| user&.create_courses_right(self).present? } can :create_courses # allow teachers to view term dates - given { |user| self.root_account? && !self.site_admin? && self.enrollments.active.of_instructor_type.where(:user_id => user).exists? } + given { |user| root_account? && !site_admin? && enrollments.active.of_instructor_type.where(:user_id => user).exists? } can :read_terms # any logged in user can read global outcomes, but must be checked against the site admin - given { |user| self.site_admin? && user } + given { |user| site_admin? && user } can :read_global_outcomes # any user with an association to this account can read the outcomes in the account - given { |user| user && self.user_account_associations.where(user_id: user).exists? } + given { |user| user && user_account_associations.where(user_id: user).exists? } can :read_outcomes # any user with an admin enrollment in one of the courses can read - given { |user| user && self.courses.where(:id => user.enrollments.active.admin.pluck(:course_id)).exists? } + given { |user| user && courses.where(:id => user.enrollments.active.admin.pluck(:course_id)).exists? } can :read - given { |user| self.grants_right?(user, :lti_add_edit) } + given { |user| grants_right?(user, :lti_add_edit) } can :create_tool_manually - given { |user| !self.site_admin? && self.root_account? && self.grants_right?(user, :manage_site_settings) } + given { |user| !site_admin? && root_account? && grants_right?(user, :manage_site_settings) } can :manage_privacy_settings given do |user| - self.root_account? && self.grants_right?(user, :read_roster) && - (self.grants_right?(user, :view_notifications) || Account.site_admin.grants_right?(user, :read_messages)) + root_account? && grants_right?(user, :read_roster) && + (grants_right?(user, :view_notifications) || Account.site_admin.grants_right?(user, :read_messages)) end can :view_bounced_emails end @@ -1360,8 +1360,8 @@ def reload(*) alias_method :destroy_permanently!, :destroy def destroy - self.transaction do - self.account_users.update_all(workflow_state: 'deleted') + transaction do + account_users.update_all(workflow_state: 'deleted') self.workflow_state = 'deleted' self.deleted_at = Time.now.utc save! @@ -1370,19 +1370,19 @@ def destroy def to_atom Atom::Entry.new do |entry| - entry.title = self.name - entry.updated = self.updated_at - entry.published = self.created_at + entry.title = name + entry.updated = updated_at + entry.published = created_at entry.links << Atom::Link.new(:rel => 'alternate', - :href => "/accounts/#{self.id}") + :href => "/accounts/#{id}") end end def default_enrollment_term return @default_enrollment_term if @default_enrollment_term - if self.root_account? - @default_enrollment_term = GuardRail.activate(:primary) { self.enrollment_terms.active.where(name: EnrollmentTerm::DEFAULT_TERM_NAME).first_or_create } + if root_account? + @default_enrollment_term = GuardRail.activate(:primary) { enrollment_terms.active.where(name: EnrollmentTerm::DEFAULT_TERM_NAME).first_or_create } end end @@ -1406,46 +1406,46 @@ def delegated_authentication? end def forgot_password_external_url - self.change_password_url + change_password_url end def auth_discovery_url=(url) - self.settings[:auth_discovery_url] = url + settings[:auth_discovery_url] = url end def auth_discovery_url - self.settings[:auth_discovery_url] + settings[:auth_discovery_url] end def login_handle_name=(handle_name) - self.settings[:login_handle_name] = handle_name + settings[:login_handle_name] = handle_name end def login_handle_name - self.settings[:login_handle_name] + settings[:login_handle_name] end def change_password_url=(change_password_url) - self.settings[:change_password_url] = change_password_url + settings[:change_password_url] = change_password_url end def change_password_url - self.settings[:change_password_url] + settings[:change_password_url] end def unknown_user_url=(unknown_user_url) - self.settings[:unknown_user_url] = unknown_user_url + settings[:unknown_user_url] = unknown_user_url end def unknown_user_url - self.settings[:unknown_user_url] + settings[:unknown_user_url] end def validate_auth_discovery_url - return if self.settings[:auth_discovery_url].blank? + return if settings[:auth_discovery_url].blank? begin - value, _uri = CanvasHttp.validate_url(self.settings[:auth_discovery_url]) + value, _uri = CanvasHttp.validate_url(settings[:auth_discovery_url]) self.auth_discovery_url = value rescue URI::Error, ArgumentError errors.add(:discovery_url, t('errors.invalid_discovery_url', "The discovery URL is not valid")) @@ -1453,7 +1453,7 @@ def validate_auth_discovery_url end def validate_help_links - links = self.settings[:custom_help_links] + links = settings[:custom_help_links] return if links.blank? link_errors = HelpLinks.validate_links(links) @@ -1491,11 +1491,11 @@ def no_active_sub_accounts end def find_courses(string) - self.all_courses.select { |c| c.name.match(string) } + all_courses.select { |c| c.name.match(string) } end def find_users(string) - self.pseudonyms.map(&:user).select { |u| u.name.match(string) } + pseudonyms.map(&:user).select { |u| u.name.match(string) } end class << self @@ -1523,7 +1523,7 @@ def clear_special_account_cache!(force = false) def define_special_account(key, name = nil) name ||= key.to_s.titleize - self.special_account_list << key + special_account_list << key instance_eval <<~RUBY, __FILE__, __LINE__ + 1 def self.#{key}(force_create = false) get_special_account(:#{key}, #{name.inspect}, force_create) @@ -1539,7 +1539,7 @@ def all_special_accounts define_special_account(:site_admin) # Account.site_admin def clear_special_account_cache_if_special - if self.shard == Shard.birth && Account.special_account_ids.values.map(&:to_i).include?(self.id) + if shard == Shard.birth && Account.special_account_ids.values.map(&:to_i).include?(id) Account.clear_special_account_cache!(true) end end @@ -1616,12 +1616,12 @@ def unless_dummy end def display_name - self.name + name end # Updates account associations for all the courses and users associated with this account def update_account_associations - self.shard.activate do + shard.activate do account_chain_cache = {} all_user_ids = Set.new @@ -1644,9 +1644,9 @@ def update_account_associations end # Make sure we have all users with existing account associations. - all_user_ids.merge self.user_account_associations.pluck(:user_id) + all_user_ids.merge user_account_associations.pluck(:user_id) if root_account? - all_user_ids.merge self.pseudonyms.active.pluck(:user_id) + all_user_ids.merge pseudonyms.active.pluck(:user_id) end # Update the users' associations as well @@ -1661,33 +1661,33 @@ def self.update_all_update_account_associations end def course_count - self.courses.active.count + courses.active.count end def sub_account_count - self.sub_accounts.active.count + sub_accounts.active.count end def user_count - self.user_account_associations.count + user_account_associations.count end def current_sis_batch - if (current_sis_batch_id = self.read_attribute(:current_sis_batch_id)) && current_sis_batch_id.present? - self.sis_batches.where(id: current_sis_batch_id).first + if (current_sis_batch_id = read_attribute(:current_sis_batch_id)) && current_sis_batch_id.present? + sis_batches.where(id: current_sis_batch_id).first end end def turnitin_settings return @turnitin_settings if defined?(@turnitin_settings) - if self.turnitin_account_id.present? && self.turnitin_shared_secret.present? + if turnitin_account_id.present? && turnitin_shared_secret.present? if settings[:enable_turnitin] - @turnitin_settings = [self.turnitin_account_id, self.turnitin_shared_secret, - self.turnitin_host] + @turnitin_settings = [turnitin_account_id, turnitin_shared_secret, + turnitin_host] end else - @turnitin_settings = self.parent_account.try(:turnitin_settings) + @turnitin_settings = parent_account.try(:turnitin_settings) end end @@ -1718,7 +1718,7 @@ def self_enrollment_allowed?(course) def allow_self_enrollment!(setting = 'any') settings[:self_enrollment] = setting - self.save! + save! end TAB_COURSES = 0 @@ -1753,34 +1753,34 @@ def external_tool_tabs(opts, user) end def tabs_available(user = nil, opts = {}) - manage_settings = user && self.grants_right?(user, :manage_account_settings) + manage_settings = user && grants_right?(user, :manage_account_settings) tabs = [] if root_account.site_admin? - tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) - tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) + tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && grants_right?(user, :read_roster) + tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && grants_right?(user, :manage_role_overrides) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if root_account? && manage_settings - tabs << { :id => TAB_PLUGINS, :label => t("#account.tab_plugins", "Plugins"), :css_class => "plugins", :href => :plugins_path, :no_args => true } if root_account? && self.grants_right?(user, :manage_site_settings) - tabs << { :id => TAB_RELEASE_NOTES, :label => t("Release Notes"), :css_class => "release_notes", :href => :account_release_notes_manage_path } if root_account? && ReleaseNote.enabled? && self.grants_right?(user, :manage_release_notes) - tabs << { :id => TAB_JOBS, :label => t("#account.tab_jobs", "Jobs"), :css_class => "jobs", :href => :jobs_path, :no_args => true } if root_account? && self.grants_right?(user, :view_jobs) + tabs << { :id => TAB_PLUGINS, :label => t("#account.tab_plugins", "Plugins"), :css_class => "plugins", :href => :plugins_path, :no_args => true } if root_account? && grants_right?(user, :manage_site_settings) + tabs << { :id => TAB_RELEASE_NOTES, :label => t("Release Notes"), :css_class => "release_notes", :href => :account_release_notes_manage_path } if root_account? && ReleaseNote.enabled? && grants_right?(user, :manage_release_notes) + tabs << { :id => TAB_JOBS, :label => t("#account.tab_jobs", "Jobs"), :css_class => "jobs", :href => :jobs_path, :no_args => true } if root_account? && grants_right?(user, :view_jobs) else - tabs << { :id => TAB_COURSES, :label => t('#account.tab_courses', "Courses"), :css_class => 'courses', :href => :account_path } if user && self.grants_right?(user, :read_course_list) - tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) - tabs << { :id => TAB_STATISTICS, :label => t('#account.tab_statistics', "Statistics"), :css_class => 'statistics', :href => :statistics_account_path } if user && self.grants_right?(user, :view_statistics) - tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) - if user && self.grants_right?(user, :manage_outcomes) + tabs << { :id => TAB_COURSES, :label => t('#account.tab_courses', "Courses"), :css_class => 'courses', :href => :account_path } if user && grants_right?(user, :read_course_list) + tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && grants_right?(user, :read_roster) + tabs << { :id => TAB_STATISTICS, :label => t('#account.tab_statistics', "Statistics"), :css_class => 'statistics', :href => :statistics_account_path } if user && grants_right?(user, :view_statistics) + tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && grants_right?(user, :manage_role_overrides) + if user && grants_right?(user, :manage_outcomes) tabs << { :id => TAB_OUTCOMES, :label => t('#account.tab_outcomes', "Outcomes"), :css_class => 'outcomes', :href => :account_outcomes_path } end - if self.can_see_rubrics_tab?(user) + if can_see_rubrics_tab?(user) tabs << { :id => TAB_RUBRICS, :label => t('#account.tab_rubrics', "Rubrics"), :css_class => 'rubrics', :href => :account_rubrics_path } end - tabs << { :id => TAB_GRADING_STANDARDS, :label => t('#account.tab_grading_standards', "Grading"), :css_class => 'grading_standards', :href => :account_grading_standards_path } if user && self.grants_right?(user, :manage_grades) - tabs << { :id => TAB_QUESTION_BANKS, :label => t('#account.tab_question_banks', "Question Banks"), :css_class => 'question_banks', :href => :account_question_banks_path } if user && self.grants_any_right?(user, *RoleOverride::GRANULAR_MANAGE_ASSIGNMENT_PERMISSIONS) + tabs << { :id => TAB_GRADING_STANDARDS, :label => t('#account.tab_grading_standards', "Grading"), :css_class => 'grading_standards', :href => :account_grading_standards_path } if user && grants_right?(user, :manage_grades) + tabs << { :id => TAB_QUESTION_BANKS, :label => t('#account.tab_question_banks', "Question Banks"), :css_class => 'question_banks', :href => :account_question_banks_path } if user && grants_any_right?(user, *RoleOverride::GRANULAR_MANAGE_ASSIGNMENT_PERMISSIONS) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings - tabs << { :id => TAB_FACULTY_JOURNAL, :label => t('#account.tab_faculty_journal', "Faculty Journal"), :css_class => 'faculty_journal', :href => :account_user_notes_path } if self.enable_user_notes && user && self.grants_right?(user, :manage_user_notes) - tabs << { :id => TAB_TERMS, :label => t('#account.tab_terms', "Terms"), :css_class => 'terms', :href => :account_terms_path } if self.root_account? && manage_settings - tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if self.root_account? && manage_settings - if self.root_account? && self.allow_sis_import && user && self.grants_any_right?(user, :manage_sis, :import_sis) + tabs << { :id => TAB_FACULTY_JOURNAL, :label => t('#account.tab_faculty_journal', "Faculty Journal"), :css_class => 'faculty_journal', :href => :account_user_notes_path } if enable_user_notes && user && grants_right?(user, :manage_user_notes) + tabs << { :id => TAB_TERMS, :label => t('#account.tab_terms', "Terms"), :css_class => 'terms', :href => :account_terms_path } if root_account? && manage_settings + tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if root_account? && manage_settings + if root_account? && allow_sis_import && user && grants_any_right?(user, :manage_sis, :import_sis) tabs << { id: TAB_SIS_IMPORT, label: t('#account.tab_sis_import', "SIS Import"), css_class: 'sis_import', href: :account_sis_import_path } end @@ -1788,7 +1788,7 @@ def tabs_available(user = nil, opts = {}) tabs << { :id => TAB_BRAND_CONFIGS, :label => t('#account.tab_brand_configs', "Themes"), :css_class => 'brand_configs', :href => :account_brand_configs_path } if manage_settings && branding_allowed? - if root_account? && self.grants_right?(user, :manage_developer_keys) + if root_account? && grants_right?(user, :manage_developer_keys) tabs << { :id => TAB_DEVELOPER_KEYS, :label => t("#account.tab_developer_keys", "Developer Keys"), :css_class => "developer_keys", :href => :account_developer_keys_path, account_id: root_account.id } end @@ -1805,12 +1805,12 @@ def tabs_available(user = nil, opts = {}) } end tabs << { :id => TAB_SETTINGS, :label => t('#account.tab_settings', "Settings"), :css_class => 'settings', :href => :account_settings_path } - tabs.delete_if { |t| t[:visibility] == 'admins' } unless self.grants_right?(user, :manage) + tabs.delete_if { |t| t[:visibility] == 'admins' } unless grants_right?(user, :manage) tabs end def can_see_rubrics_tab?(user) - user && self.grants_right?(user, :manage_rubrics) + user && grants_right?(user, :manage_rubrics) end def can_see_admin_tools_tab?(user) @@ -1818,7 +1818,7 @@ def can_see_admin_tools_tab?(user) admin_tool_permissions = RoleOverride.manageable_permissions(self).find_all { |p| p[1][:admin_tool] } admin_tool_permissions.any? do |p| - self.grants_right?(user, p.first) + grants_right?(user, p.first) end end @@ -1858,7 +1858,7 @@ def set_service_availability(service, enable) service = service.to_sym raise "Invalid Service" unless AccountServices.allowable_services[service] - allowed_service_names = (self.allowed_services || "").split(",").compact + allowed_service_names = (allowed_services || "").split(",").compact # rubocop:disable Style/IdenticalConditionalBranches common line needs to happen after the conditional if allowed_service_names.count > 0 && !['+', '-'].include?(allowed_service_names[0][0, 1]) allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } @@ -1892,8 +1892,8 @@ def allowed_services_hash return @allowed_services_hash if @allowed_services_hash account_allowed_services = AccountServices.default_allowable_services - if self.allowed_services - allowed_service_names = self.allowed_services.split(",").compact + if allowed_services + allowed_service_names = allowed_services.split(",").compact if allowed_service_names.count > 0 unless ['+', '-'].member?(allowed_service_names[0][0, 1]) @@ -1932,9 +1932,9 @@ def service_enabled?(service) service = service.to_sym case service when :none - self.allowed_services_hash.empty? + allowed_services_hash.empty? else - self.allowed_services_hash.key?(service) + allowed_services_hash.key?(service) end end @@ -1958,7 +1958,7 @@ def find_child(child_id) end def manually_created_courses_account - return self.root_account.manually_created_courses_account unless self.root_account? + return root_account.manually_created_courses_account unless root_account? display_name = t('#account.manually_created_courses', "Manually-Created Courses") acct = manually_created_courses_account_from_settings @@ -1967,10 +1967,10 @@ def manually_created_courses_account transaction do lock! acct = manually_created_courses_account_from_settings - acct ||= self.sub_accounts.where(name: display_name).first_or_create! # for backwards compatibility - if acct.id != self.settings[:manually_created_courses_account_id] - self.settings[:manually_created_courses_account_id] = acct.id - self.save! + acct ||= sub_accounts.where(name: display_name).first_or_create! # for backwards compatibility + if acct.id != settings[:manually_created_courses_account_id] + settings[:manually_created_courses_account_id] = acct.id + save! end end end @@ -1979,9 +1979,9 @@ def manually_created_courses_account end def manually_created_courses_account_from_settings - acct_id = self.settings[:manually_created_courses_account_id] - acct = self.sub_accounts.where(id: acct_id).first if acct_id.present? - acct = nil if acct.present? && acct.root_account_id != self.id + acct_id = settings[:manually_created_courses_account_id] + acct = sub_accounts.where(id: acct_id).first if acct_id.present? + acct = nil if acct.present? && acct.root_account_id != id acct end private :manually_created_courses_account_from_settings @@ -1997,8 +1997,8 @@ def trust_exists? end def user_list_search_mode_for(user) - return :preferred if self.root_account.open_registration? - return :preferred if self.root_account.grants_right?(user, :manage_user_logins) + return :preferred if root_account.open_registration? + return :preferred if root_account.grants_right?(user, :manage_user_logins) :closed end @@ -2035,16 +2035,16 @@ def format_referer(referer_url) end def trusted_referers=(value) - self.settings[:trusted_referers] = unless value.blank? - value.split(',').filter_map { |referer_url| format_referer(referer_url) }.join(',') - end + settings[:trusted_referers] = unless value.blank? + value.split(',').filter_map { |referer_url| format_referer(referer_url) }.join(',') + end end def trusted_referer?(referer_url) - return if !self.settings.key?(:trusted_referers) || self.settings[:trusted_referers].blank? + return if !settings.key?(:trusted_referers) || settings[:trusted_referers].blank? if (referer_with_port = format_referer(referer_url)) - self.settings[:trusted_referers].split(',').include?(referer_with_port) + settings[:trusted_referers].split(',').include?(referer_with_port) end end @@ -2070,8 +2070,8 @@ def create_default_objects work = -> do default_enrollment_term enable_canvas_authentication - TermsOfService.ensure_terms_for_account(self, true) if self.root_account? && !TermsOfService.skip_automatic_terms_creation - create_built_in_roles if self.root_account? + TermsOfService.ensure_terms_for_account(self, true) if root_account? && !TermsOfService.skip_automatic_terms_creation + create_built_in_roles if root_account? end return work.call if Rails.env.test? @@ -2079,13 +2079,13 @@ def create_default_objects end def create_built_in_roles - self.shard.activate do + shard.activate do Role::BASE_TYPES.each do |base_type| role = Role.new role.name = base_type role.base_role_type = base_type role.workflow_state = :built_in - role.root_account_id = self.id + role.root_account_id = id role.save! end end @@ -2102,12 +2102,12 @@ def update_terms_of_service(terms_params) if terms.custom? TermsOfServiceContent.ensure_content_for_account(self) - self.terms_of_service_content.update_attribute(:content, terms_params[:content]) if terms_params[:content] + terms_of_service_content.update_attribute(:content, terms_params[:content]) if terms_params[:content] end if terms.changed? unless terms.save - self.errors.add(:terms_of_service, t("Terms of Service attributes not valid")) + errors.add(:terms_of_service, t("Terms of Service attributes not valid")) end end end @@ -2121,16 +2121,16 @@ def dashboard_views def default_dashboard_view=(view) return unless dashboard_views.include?(view) - self.settings[:default_dashboard_view] = view + settings[:default_dashboard_view] = view end def default_dashboard_view - @default_dashboard_view ||= self.settings[:default_dashboard_view] + @default_dashboard_view ||= settings[:default_dashboard_view] end # Forces the default setting to overwrite each user's preference def update_user_dashboards - User.where(id: self.user_account_associations.select(:user_id)) + User.where(id: user_account_associations.select(:user_id)) .where("#{User.table_name}.preferences LIKE ?", "%:dashboard_view:%") .find_in_batches do |batch| users = batch.reject { |user| @@ -2173,7 +2173,7 @@ def available_course_visibility_override_options(options = nil) end def user_needs_verification?(user) - self.require_confirmed_email? && (user.nil? || user.cached_active_emails.none?) + require_confirmed_email? && (user.nil? || user.cached_active_emails.none?) end def allow_disable_post_to_sis_when_grading_period_closed? diff --git a/app/models/account/settings.rb b/app/models/account/settings.rb index 4bae0223fb7ff..86e222358f18b 100644 --- a/app/models/account/settings.rb +++ b/app/models/account/settings.rb @@ -24,23 +24,23 @@ def add_setting(setting, opts = nil) opts[:hash] = true opts[:values] = [:value, :locked] - self.class_eval "def #{setting}; cached_inherited_setting(:#{setting}); end", __FILE__, __LINE__ + class_eval "def #{setting}; cached_inherited_setting(:#{setting}); end", __FILE__, __LINE__ elsif opts && opts[:boolean] && opts.key?(:default) if opts[:default] # if the default is true, we want a nil result to evaluate to true. # this prevents us from having to backfill true values into a # serialized column, which would be expensive. - self.class_eval "def #{setting}?; settings[:#{setting}] != false; end", __FILE__, __LINE__ + class_eval "def #{setting}?; settings[:#{setting}] != false; end", __FILE__, __LINE__ else # if the default is not true, we can fall back to a straight boolean. - self.class_eval "def #{setting}?; !!settings[:#{setting}]; end", __FILE__, __LINE__ + class_eval "def #{setting}?; !!settings[:#{setting}]; end", __FILE__, __LINE__ end end - self.account_settings_options[setting.to_sym] = opts || {} + account_settings_options[setting.to_sym] = opts || {} end def inheritable_settings - self.account_settings_options.select { |_k, v| v[:inheritable] }.keys + account_settings_options.select { |_k, v| v[:inheritable] }.keys end end @@ -51,9 +51,9 @@ def self.included(klass) end def cached_inherited_setting(setting) - self.shard.activate do + shard.activate do RequestCache.cache("inherited_settings", self, setting) do - Rails.cache.fetch([setting, self.global_id].cache_key) do + Rails.cache.fetch([setting, global_id].cache_key) do calculate_inherited_setting(setting) end end @@ -64,7 +64,7 @@ def cached_inherited_setting(setting) # otherwise use the last explicitly set value def calculate_inherited_setting(setting) inherited_hash = { :locked => false, :value => self.class.account_settings_options[setting][:default] } - self.account_chain.reverse_each do |acc| + account_chain.reverse_each do |acc| current_hash = acc.settings[setting] next if current_hash.nil? diff --git a/app/models/account_notification.rb b/app/models/account_notification.rb index 2b198bc4fb14d..64c72c585860a 100644 --- a/app/models/account_notification.rb +++ b/app/models/account_notification.rb @@ -38,8 +38,8 @@ class AccountNotification < ActiveRecord::Base validates :months_in_display_cycle, inclusion: { in: 1..48, allow_nil: true } def validate_dates - if self.start_at && self.end_at - errors.add(:end_at, t('errors.invalid_account_notification_end_at', "Account notification end time precedes start time")) if self.end_at < self.start_at + if start_at && end_at + errors.add(:end_at, t('errors.invalid_account_notification_end_at', "Account notification end time precedes start time")) if end_at < start_at end end @@ -47,24 +47,24 @@ def create_alert if start_at > Time.zone.now delay(run_at: start_at, on_conflict: :overwrite, - singleton: "create_notification_alert:#{self.global_id}") + singleton: "create_notification_alert:#{global_id}") .create_alert return end - return unless self.account.root_account? + return unless account.root_account? - roles = self.account_notification_roles.map(&:role_name) + roles = account_notification_roles.map(&:role_name) return if roles.count > 0 && (roles & ['StudentEnrollment', 'ObserverEnrollment']).none? - thresholds = ObserverAlertThreshold.active.where(observer: User.of_account(self.account), alert_type: 'institution_announcement') + thresholds = ObserverAlertThreshold.active.where(observer: User.of_account(account), alert_type: 'institution_announcement') .where.not(id: ObserverAlert.where(context: self).select(:observer_alert_threshold_id)) thresholds.find_each do |threshold| ObserverAlert.create(student: threshold.student, observer: threshold.observer, observer_alert_threshold: threshold, context: self, - alert_type: 'institution_announcement', action_date: self.start_at, + alert_type: 'institution_announcement', action_date: start_at, title: I18n.t('Institution announcement: "%{announcement_title}"', { - announcement_title: self.subject + announcement_title: subject })) end end @@ -82,7 +82,7 @@ def past? def self.for_user_and_account(user, root_account, include_past: false) GuardRail.activate(:secondary) do if root_account.site_admin? - current = self.for_account(root_account, include_past: include_past) + current = for_account(root_account, include_past: include_past) else course_ids = user.enrollments.active_or_pending_by_date.shard(user.in_region_associated_shards).distinct.pluck(:course_id) # fetch sharded course ids # and then fetch account_ids separately - using pluck on a joined column doesn't give relative ids @@ -92,7 +92,7 @@ def self.for_user_and_account(user, root_account, include_past: false) .joins(:account).where(accounts: { workflow_state: 'active' }) .distinct.pluck(:account_id).uniq all_account_ids = Account.multi_account_chain_ids(all_account_ids) # get all parent sub-accounts too - current = self.for_account(root_account, all_account_ids, include_past: include_past) + current = for_account(root_account, all_account_ids, include_past: include_past) end user_role_ids = {} @@ -160,7 +160,7 @@ def self.for_user_and_account(user, root_account, include_past: false) # on user id) current.reject! do |announcement| if (months_in_period = announcement.months_in_display_cycle) - !self.display_for_user?(user.id, months_in_period) + !display_for_user?(user.id, months_in_period) end end @@ -297,30 +297,30 @@ def self.display_for_user?(user_id, months_in_period, current_time = Time.now.ut set_broadcast_policy do |p| p.dispatch :account_notification - p.to { self.message_recipients } + p.to { message_recipients } p.whenever { |record| record.should_send_message? && record.message_recipients.present? } end def send_message_not_set_for_site_admin - if self.send_message? && self.account.site_admin? + if send_message? && account.site_admin? # i mean maybe we could try but there are almost certainly better ways to send mass emails than this errors.add(:send_message, 'Cannot send messages for site admin accounts') end end def should_send_message? - self.send_message? && !self.messages_sent_at && - (self.start_at.nil? || (self.start_at < Time.now.utc)) && - (self.end_at.nil? || (self.end_at > Time.now.utc)) + send_message? && !messages_sent_at && + (start_at.nil? || (start_at < Time.now.utc)) && + (end_at.nil? || (end_at > Time.now.utc)) end def queue_message_broadcast - if self.send_message? && !self.messages_sent_at && !self.message_recipients + if send_message? && !messages_sent_at && !message_recipients delay(run_at: start_at || Time.now.utc, on_conflict: :overwrite, - singleton: "account_notification_broadcast_messages:#{self.global_id}").broadcast_messages + singleton: "account_notification_broadcast_messages:#{global_id}").broadcast_messages end end @@ -336,22 +336,22 @@ def self.users_per_message_batch end def broadcast_messages - return unless self.should_send_message? # sanity check before we start grabbing user ids + return unless should_send_message? # sanity check before we start grabbing user ids # don't try to send a message to an entire account in one job - self.applicable_user_ids.each_slice(self.class.users_per_message_batch) do |sliced_user_ids| + applicable_user_ids.each_slice(self.class.users_per_message_batch) do |sliced_user_ids| self.message_recipients = sliced_user_ids.map { |id| "user_#{id}" } - self.save # trigger the broadcast policy + save # trigger the broadcast policy ensure self.message_recipients = nil end - self.update_attribute(:messages_sent_at, Time.now.utc) + update_attribute(:messages_sent_at, Time.now.utc) end def applicable_user_ids - roles = self.account_notification_roles.preload(:role).to_a.map(&:role) + roles = account_notification_roles.preload(:role).to_a.map(&:role) GuardRail.activate(:secondary) do - self.class.applicable_user_ids_for_account_and_roles(self.account, roles) + self.class.applicable_user_ids_for_account_and_roles(account, roles) end end diff --git a/app/models/account_notification_role.rb b/app/models/account_notification_role.rb index ee4bd4ff7460a..cd8a1ad93e535 100644 --- a/app/models/account_notification_role.rb +++ b/app/models/account_notification_role.rb @@ -25,12 +25,12 @@ class AccountNotificationRole < ActiveRecord::Base before_save :resolve_cross_account_role def resolve_cross_account_role - if self.will_save_change_to_role_id? && self.role.root_account_id != self.account_notification.account.resolved_root_account_id - self.role = self.role.role_for_root_account_id(self.account_notification.account.resolved_root_account_id) + if will_save_change_to_role_id? && role.root_account_id != account_notification.account.resolved_root_account_id + self.role = role.role_for_root_account_id(account_notification.account.resolved_root_account_id) end end def role_name - self.role_id ? role.name : 'NilEnrollment' + role_id ? role.name : 'NilEnrollment' end end diff --git a/app/models/account_report.rb b/app/models/account_report.rb index f203d04810523..277b075b0ef75 100644 --- a/app/models/account_report.rb +++ b/app/models/account_report.rb @@ -40,7 +40,7 @@ def initialize(*) def add_report_runner(batch) @runners ||= [] - runners << self.account_report_runners.new(batch_items: batch, created_at: Time.zone.now, updated_at: Time.zone.now) + runners << account_report_runners.new(batch_items: batch, created_at: Time.zone.now, updated_at: Time.zone.now) end def write_report_runners @@ -75,7 +75,7 @@ def self.delete_old_rows_and_runners # There is a FK between rows and runners, so delete rows first cleanup = AccountReportRow.where("created_at { where(workflow_state: %w[running]) } @@ -72,7 +72,7 @@ def fail scope :incomplete, -> { where(workflow_state: %w[created running]) } def delete_account_report_rows - cleanup = self.account_report_rows.limit(10_000) + cleanup = account_report_rows.limit(10_000) until cleanup.delete_all < 10_000; end end end diff --git a/app/models/account_user.rb b/app/models/account_user.rb index 5b8c1ba40ba1c..a880b1966e9b7 100644 --- a/app/models/account_user.rb +++ b/app/models/account_user.rb @@ -54,52 +54,50 @@ class AccountUser < ActiveRecord::Base def clear_user_cache self.class.connection.after_transaction_commit do - self.user.touch unless User.skip_touch_for_type?(:account_users) - self.user.clear_cache_key(:account_users) + user.touch unless User.skip_touch_for_type?(:account_users) + user.clear_cache_key(:account_users) end end alias_method :destroy_permanently!, :destroy def destroy - return if self.new_record? + return if new_record? self.workflow_state = 'deleted' - self.save! + save! end def update_account_associations_if_changed - being_deleted = self.workflow_state == 'deleted' && self.workflow_state_before_last_save != 'deleted' - if (self.saved_change_to_account_id? || self.saved_change_to_user_id?) || being_deleted - if self.new_record? - return if %w[creation_pending deleted].include?(self.user.workflow_state) + being_deleted = workflow_state == 'deleted' && workflow_state_before_last_save != 'deleted' + if (saved_change_to_account_id? || saved_change_to_user_id?) || being_deleted + if new_record? + return if %w[creation_pending deleted].include?(user.workflow_state) - account_chain = self.account.account_chain + account_chain = account.account_chain associations = {} account_chain.each_with_index { |account, idx| associations[account.id] = idx } - self.user.update_account_associations(:incremental => true, :precalculated_associations => associations) + user.update_account_associations(:incremental => true, :precalculated_associations => associations) else - self.user.update_account_associations_later + user.update_account_associations_later end end end - def update_account_associations_later - self.user.update_account_associations_later - end + delegate :update_account_associations_later, to: :user def infer_defaults - self.role ||= Role.get_built_in_role('AccountAdmin', root_account_id: self.account.resolved_root_account_id) + self.role ||= Role.get_built_in_role('AccountAdmin', root_account_id: account.resolved_root_account_id) end def valid_role? return true if role.built_in? unless role.account_role? - self.errors.add(:role_id, "is not a valid account role") + errors.add(:role_id, "is not a valid account role") end - unless self.account.valid_role?(role) - self.errors.add(:role_id, "is not an available role for this account") + unless account.valid_role?(role) + errors.add(:role_id, "is not an available role for this account") end end @@ -119,7 +117,7 @@ def valid_role? set_policy do # NOTE: If modifying this, make sure `create_permissions_cache` stays accurate as well. - given { |user| self.account.grants_right?(user, :manage_account_memberships) && is_subset_of?(user) } + given { |user| account.grants_right?(user, :manage_account_memberships) && is_subset_of?(user) } can :create and can :destroy end @@ -145,19 +143,19 @@ def readable_type def account_user_registration! @account_user_registration = true - self.save! + save! @account_user_registration = false end def account_user_notification! @account_user_notification = true - self.save! + save! @account_user_notification = false end def enabled_for?(context, action) @permission_lookup ||= {} - @permission_lookup[[context.class, context.global_id, action]] ||= RoleOverride.enabled_for?(context, action, self.role, self.account) + @permission_lookup[[context.class, context.global_id, action]] ||= RoleOverride.enabled_for?(context, action, self.role, account) end def has_permission_to?(context, action) diff --git a/app/models/alert.rb b/app/models/alert.rb index 2764755176d80..ca7c61b79b9b6 100644 --- a/app/models/alert.rb +++ b/app/models/alert.rb @@ -40,7 +40,7 @@ def resolve_recipients(student_id, teachers = nil) include_student = false include_teachers = false admin_role_ids = [] - self.recipients.try(:each) do |recipient| + recipients.try(:each) do |recipient| case recipient when :student include_student = true @@ -66,11 +66,11 @@ def resolve_recipients(student_id, teachers = nil) end def infer_defaults - self.repetition = nil if self.repetition.blank? + self.repetition = nil if repetition.blank? end def as_json(**) - converted_recipients = self.recipients.to_a.map do |recipient| + converted_recipients = recipients.to_a.map do |recipient| case recipient when String find_role_by_name(recipient).id @@ -93,14 +93,14 @@ def criteria=(values) values = values.map do |params| if params[:id].present? id = params.delete(:id).to_i - criterion = self.criteria.to_ary.find { |c| c.id == id } + criterion = criteria.to_ary.find { |c| c.id == id } criterion.attributes = params else - criterion = self.criteria.build(params) + criterion = criteria.build(params) end criterion end end - self.criteria.replace(values) + criteria.replace(values) end end diff --git a/app/models/alerts/delayed_alert_sender.rb b/app/models/alerts/delayed_alert_sender.rb index fd3fb3e98ceef..edfbd553a7c0f 100644 --- a/app/models/alerts/delayed_alert_sender.rb +++ b/app/models/alerts/delayed_alert_sender.rb @@ -34,7 +34,7 @@ def self.evaluate_courses(course_ids) alerts_cache = {} Course.where(id: course_ids).find_each do |course| alerts_cache[course.account_id] ||= course.account.account_chain.map { |a| a.alerts.to_a }.flatten - self.evaluate_for_course(course, alerts_cache[course.account_id]) + evaluate_for_course(course, alerts_cache[course.account_id]) end end diff --git a/app/models/announcement.rb b/app/models/announcement.rb index 586443292ddc9..f85c0031104ce 100644 --- a/app/models/announcement.rb +++ b/app/models/announcement.rb @@ -49,8 +49,8 @@ class Announcement < DiscussionTopic } def validate_draft_state_change - _old_draft_state, new_draft_state = self.changes['workflow_state'] - self.errors.add :workflow_state, I18n.t('#announcements.error_draft_state', "This topic cannot be set to draft state because it is an announcement.") if new_draft_state == 'unpublished' + _old_draft_state, new_draft_state = changes['workflow_state'] + errors.add :workflow_state, I18n.t('#announcements.error_draft_state', "This topic cannot be set to draft state because it is an announcement.") if new_draft_state == 'unpublished' end def infer_content @@ -99,34 +99,34 @@ def course_broadcast_data given { |user| self.user.present? && self.user == user } can :update and can :reply and can :read - given { |user| self.user.present? && self.user == user && self.discussion_entries.active.empty? } + given { |user| self.user.present? && self.user == user && discussion_entries.active.empty? } can :delete given do |user| - self.grants_right?(user, :read) && - (self.context.is_a?(Group) || + grants_right?(user, :read) && + (context.is_a?(Group) || (user && - (self.context.grants_right?(user, :read_as_admin) || - (self.context.is_a?(Course) && - self.context.includes_user?(user))))) + (context.grants_right?(user, :read_as_admin) || + (context.is_a?(Course) && + context.includes_user?(user))))) end can :read_replies - given { |user, session| self.context.grants_right?(user, session, :read_announcements) && self.visible_for?(user) } + given { |user, session| context.grants_right?(user, session, :read_announcements) && visible_for?(user) } can :read - given { |user, session| self.context.grants_right?(user, session, :post_to_forum) && !self.locked? } + given { |user, session| context.grants_right?(user, session, :post_to_forum) && !locked? } can :reply - given { |user, session| self.context.is_a?(Group) && self.context.grants_right?(user, session, :create_forum) } + given { |user, session| context.is_a?(Group) && context.grants_right?(user, session, :create_forum) } can :create - given { |user, session| self.context.grants_all_rights?(user, session, :read_announcements, :moderate_forum) } # admins.include?(user) } + given { |user, session| context.grants_all_rights?(user, session, :read_announcements, :moderate_forum) } # admins.include?(user) } can :update and can :read_as_admin and can :delete and can :reply and can :create and can :read and can :attach given do |user, session| - self.allow_rating && (!self.only_graders_can_rate || - self.context.grants_right?(user, session, :manage_grades)) + allow_rating && (!only_graders_can_rate || + context.grants_right?(user, session, :manage_grades)) end can :rate end @@ -162,9 +162,9 @@ def assignment def create_alert return if !saved_changes.key?('workflow_state') || saved_changes['workflow_state'][1] != 'active' - return if self.context_type != 'Course' + return if context_type != 'Course' - observer_enrollments = self.course.enrollments.active.where(type: 'ObserverEnrollment') + observer_enrollments = course.enrollments.active.where(type: 'ObserverEnrollment') observer_enrollments.each do |enrollment| observer = enrollment.user student = enrollment.associated_user @@ -172,10 +172,10 @@ def create_alert next unless threshold ObserverAlert.create!(observer: observer, student: student, observer_alert_threshold: threshold, - context: self, alert_type: 'course_announcement', action_date: self.updated_at, + context: self, alert_type: 'course_announcement', action_date: updated_at, title: I18n.t("Course announcement: \"%{title}\" in %{course_code}", { title: self.title, - course_code: self.course.course_code + course_code: course.course_code })) end end diff --git a/app/models/anonymous_or_moderation_event.rb b/app/models/anonymous_or_moderation_event.rb index 0758fb592d8d4..af5ba6988ae70 100644 --- a/app/models/anonymous_or_moderation_event.rb +++ b/app/models/anonymous_or_moderation_event.rb @@ -111,7 +111,7 @@ class AnonymousOrModerationEvent < ApplicationRecord end def self.events_for_submission(assignment_id:, submission_id:) - self.where(assignment_id: assignment_id, submission_id: [nil, submission_id]).order(:created_at) + where(assignment_id: assignment_id, submission_id: [nil, submission_id]).order(:created_at) end EVENT_TYPES.each do |event_type| diff --git a/app/models/appointment_group.rb b/app/models/appointment_group.rb index cc8724e1431bb..4ecf6f92e7e7a 100644 --- a/app/models/appointment_group.rb +++ b/app/models/appointment_group.rb @@ -385,7 +385,7 @@ def all_appointments_filled? return false unless participants_per_appointment appointments_participants.count >= appointments.sum( - sanitize_sql(['COALESCE(participants_per_appointment, ?)', self.participants_per_appointment]) + sanitize_sql(['COALESCE(participants_per_appointment, ?)', participants_per_appointment]) ) end @@ -399,7 +399,7 @@ def participant_for(user) else # can't have more than one group_category group_categories = sub_contexts.find_all { |sc| sc.instance_of? GroupCategory } - raise "inconsistent appointment group: #{self.id} #{group_categories}" if group_categories.length > 1 + raise "inconsistent appointment group: #{id} #{group_categories}" if group_categories.length > 1 group_category_id = group_categories.first.id user.current_groups.detect { |g| g.group_category_id == group_category_id } @@ -432,7 +432,7 @@ def update_appointments .index_with { |attr| send(attr) } if @contexts_changed - changed[:root_account_id] = self.context&.root_account_id + changed[:root_account_id] = context&.root_account_id changed[:effective_context_code] = contexts.map(&:asset_string).join(",") end @@ -495,7 +495,7 @@ def destroy(updating_user) transaction do self.workflow_state = 'deleted' save! - self.appointments.map do |a| + appointments.map do |a| a.updating_user = updating_user a.destroy(false) end diff --git a/app/models/assessment_question.rb b/app/models/assessment_question.rb index aecd743d05853..3630e69ededac 100644 --- a/app/models/assessment_question.rb +++ b/app/models/assessment_question.rb @@ -51,26 +51,26 @@ class AssessmentQuestion < ActiveRecord::Base set_policy do given do |user, session| - self.context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) + context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) end can :read and can :create and can :update and can :delete given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_add) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_add) end can :read and can :create given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_delete) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_delete) end can :read and can :delete end def user_can_see_through_quiz_question?(user, session = nil) - self.shard.activate do - quiz_ids = self.quiz_questions.distinct.pluck(:quiz_id) + shard.activate do + quiz_ids = quiz_questions.distinct.pluck(:quiz_id) quiz_ids.any? && Quizzes::Quiz.where(:id => quiz_ids, :context_type => "Course", :context_id => Enrollment.where(user_id: user).active.select(:course_id)).to_a.any? { |q| q.grants_right?(user, session, :read) } end @@ -84,15 +84,15 @@ def infer_defaults end self.question_data[:name] = self.question_data[:question_name] end - self.name = self.question_data[:question_name] || self.name - self.assessment_question_bank ||= AssessmentQuestionBank.unfiled_for_context(self.initial_context) + self.name = self.question_data[:question_name] || name + self.assessment_question_bank ||= AssessmentQuestionBank.unfiled_for_context(initial_context) end def translate_links_if_changed # this has to be in an after_save, because translate_links may create attachments # with this question as the context, and if this question does not exist yet, # creating that attachment will fail. - if self.saved_change_to_question_data? && !@skip_translate_links + if saved_change_to_question_data? && !@skip_translate_links AssessmentQuestion.connection.after_transaction_commit do translate_links end @@ -182,21 +182,21 @@ def translate_links self.question_data = hash @skip_translate_links = true - self.save! + save! @skip_translate_links = false end end def data res = self.question_data || HashWithIndifferentAccess.new - res[:assessment_question_id] = self.id + res[:assessment_question_id] = id res[:question_name] = t :default_question_name, "Question" if res[:question_name].blank? # TODO: there's a potential id conflict here, where if a quiz # has some questions manually created and some pulled from a # bank, it's possible that a manual question's id could match # an assessment_question's id. This would prevent the user # from being able to answer both questions when taking the quiz. - res[:id] = self.id + res[:id] = id res end @@ -236,17 +236,17 @@ def edited_independent_of_quiz_question end def editable_by?(question) - if self.independently_edited? || + if independently_edited? || # If the assessment_question was created long before the quiz_question, # then the assessment question must have been created on its own, which means # it shouldn't be affected by changes to the quiz_question since it wasn't # based on the quiz_question to begin with - (!self.new_record? && question.assessment_question_id == self.id && question.created_at && self.created_at < question.created_at + 5.minutes && self.created_at > question.created_at + 30.seconds) || + (!new_record? && question.assessment_question_id == id && question.created_at && created_at < question.created_at + 5.minutes && created_at > question.created_at + 30.seconds) || (self.assessment_question_bank && self.assessment_question_bank.title != AssessmentQuestionBank.default_unfiled_title) || (question.is_a?(Quizzes::QuizQuestion) && question.generated?) false else - self.new_record? || (quiz_questions.count <= 1 && question.assessment_question_id == self.id) + new_record? || (quiz_questions.count <= 1 && question.assessment_question_id == id) end end @@ -318,7 +318,7 @@ def destroy self.assessment_question_bank.touch self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - self.save + save end def self.parse_question(qdata, assessment_question = nil) @@ -361,7 +361,7 @@ def self.variable_id(variable) def clone_for(question_bank, dup = nil, **) dup ||= AssessmentQuestion.new - self.attributes.except("id", "question_data").each do |key, val| + attributes.except("id", "question_data").each do |key, val| dup.send("#{key}=", val) end dup.assessment_question_bank_id = question_bank diff --git a/app/models/assessment_question_bank.rb b/app/models/assessment_question_bank.rb index 5d3508c2edd0a..405ced64cfa24 100644 --- a/app/models/assessment_question_bank.rb +++ b/app/models/assessment_question_bank.rb @@ -42,37 +42,37 @@ class AssessmentQuestionBank < ActiveRecord::Base set_policy do given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :read_question_banks) && - self.context.grants_right?(user, session, :manage_assignments) + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :read_question_banks) && + context.grants_right?(user, session, :manage_assignments) end can :read and can :create and can :update and can :delete and can :manage given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :read_question_banks) && - self.context.grants_right?(user, session, :manage_assignments_add) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :read_question_banks) && + context.grants_right?(user, session, :manage_assignments_add) end can :read and can :create given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :read_question_banks) && - self.context.grants_right?(user, session, :manage_assignments_edit) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :read_question_banks) && + context.grants_right?(user, session, :manage_assignments_edit) end can :read and can :update and can :manage given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :read_question_banks) && - self.context.grants_right?(user, session, :manage_assignments_delete) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :read_question_banks) && + context.grants_right?(user, session, :manage_assignments_delete) end can :read and can :delete - given { |user, session| self.context.grants_right?(user, session, :read_question_banks) } + given { |user, session| context.grants_right?(user, session, :read_question_banks) } can :read - given { |user| user && self.assessment_question_bank_users.where(:user_id => user).exists? } + given { |user| user && assessment_question_bank_users.where(:user_id => user).exists? } can :read end @@ -89,21 +89,21 @@ def self.unfiled_for_context(context) end def cached_context_short_name - @cached_context_name ||= Rails.cache.fetch(['short_name_lookup', self.context_code].cache_key) do - self.context.short_name rescue "" + @cached_context_name ||= Rails.cache.fetch(['short_name_lookup', context_code].cache_key) do + context.short_name rescue "" end end def assessment_question_count - self.assessment_questions.active.count + assessment_questions.active.count end def context_code - "#{self.context_type.underscore}_#{self.context_id}" + "#{context_type.underscore}_#{context_id}" end def infer_defaults - self.title = t(:default_title, "No Name - %{course}", :course => self.context.name) if self.title.blank? + self.title = t(:default_title, "No Name - %{course}", :course => context.name) if title.blank? end def alignments=(alignments) @@ -149,7 +149,7 @@ def bookmark_for(user, do_bookmark = true) end def bookmarked_for?(user) - user && self.assessment_question_bank_users.where(user_id: user).exists? + user && assessment_question_bank_users.where(user_id: user).exists? end def select_for_submission(quiz_id, quiz_group_id, count, exclude_ids = [], duplicate_index = 0) @@ -168,7 +168,7 @@ def select_for_submission(quiz_id, quiz_group_id, count, exclude_ids = [], dupli def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - self.save + save end # clear out all questions so that the bank can be replaced. this is currently diff --git a/app/models/assessment_request.rb b/app/models/assessment_request.rb index 02e7f36b80741..f9962657ff2f8 100644 --- a/app/models/assessment_request.rb +++ b/app/models/assessment_request.rb @@ -56,14 +56,14 @@ def course_broadcast_data set_broadcast_policy do |p| p.dispatch :rubric_assessment_submission_reminder - p.to { self.assessor } + p.to { assessor } p.whenever { should_send_reminder? && active_rubric_association? } p.data { course_broadcast_data } p.dispatch :peer_review_invitation - p.to { self.assessor } + p.to { assessor } p.whenever { should_send_reminder? && !active_rubric_association? } @@ -86,25 +86,25 @@ def course_broadcast_data set_policy do given { |user, session| - self.can_read_assessment_user_name?(user, session) + can_read_assessment_user_name?(user, session) } can :read_assessment_user end def can_read_assessment_user_name?(user, session) - !self.considered_anonymous? || - self.user_id == user.id || - self.submission.assignment.context.grants_right?(user, session, :view_all_grades) + !considered_anonymous? || + user_id == user.id || + submission.assignment.context.grants_right?(user, session, :view_all_grades) end def considered_anonymous? - self.submission.assignment.anonymous_peer_reviews? + submission.assignment.anonymous_peer_reviews? end def send_reminder! @send_reminder = true self.updated_at = Time.now - self.save! + save! ensure @send_reminder = nil end @@ -124,7 +124,7 @@ def context end def assessor_name - self.rubric_assessment.assessor_name rescue ((self.assessor.name rescue nil) || t("#unknown", "Unknown")) + rubric_assessment.assessor_name rescue ((assessor.name rescue nil) || t("#unknown", "Unknown")) end def incomplete? @@ -132,10 +132,10 @@ def incomplete? end on_create_send_to_streams do - self.assessor + assessor end on_update_send_to_streams do - self.assessor + assessor end workflow do @@ -148,15 +148,15 @@ def incomplete? end def asset_title - (self.asset.assignment.title rescue self.asset.title) rescue t("#unknown", "Unknown") + (asset.assignment.title rescue asset.title) rescue t("#unknown", "Unknown") end def comment_added - self.workflow_state = "completed" unless active_rubric_association? && self.rubric_association.rubric + self.workflow_state = "completed" unless active_rubric_association? && rubric_association.rubric end def asset_user_name - self.asset.user.name rescue t("#unknown", "Unknown") + asset.user.name rescue t("#unknown", "Unknown") end def self.serialization_excludes @@ -165,12 +165,12 @@ def self.serialization_excludes def update_planner_override if saved_change_to_workflow_state? && workflow_state_before_last_save == 'assigned' && workflow_state == 'completed' - override = PlannerOverride.find_by(plannable_id: self.id, plannable_type: 'AssessmentRequest', user: assessor) + override = PlannerOverride.find_by(plannable_id: id, plannable_type: 'AssessmentRequest', user: assessor) override.update(marked_complete: true) if override.present? end end def active_rubric_association? - !!self.rubric_association&.active? + !!rubric_association&.active? end end diff --git a/app/models/asset_user_access.rb b/app/models/asset_user_access.rb index fa3d3b313f65c..5cf8428163a4b 100644 --- a/app/models/asset_user_access.rb +++ b/app/models/asset_user_access.rb @@ -53,7 +53,7 @@ def infer_root_account_id(asset_for_root_account_id = nil) end def category - self.asset_category + asset_category end def infer_defaults @@ -78,24 +78,24 @@ def display_name def asset_display_name return nil unless asset - if self.asset.respond_to?(:title) && !self.asset.title.nil? + if asset.respond_to?(:title) && !asset.title.nil? asset.title - elsif self.asset.is_a? Enrollment + elsif asset.is_a? Enrollment asset.user.name - elsif self.asset.respond_to?(:name) && !self.asset.name.nil? + elsif asset.respond_to?(:name) && !asset.name.nil? asset.name else - self.asset_code + asset_code end end def context_code - "#{self.context_type.underscore}_#{self.context_id}" rescue nil + "#{context_type.underscore}_#{context_id}" rescue nil end def readable_name(include_group_name: true) - if self.asset_code&.include?(':') - split = self.asset_code.split(":") + if asset_code&.include?(':') + split = asset_code.split(":") if split[1].match?(/course_\d+/) case split[0] @@ -162,14 +162,14 @@ def readable_name(include_group_name: true) when "files" t('User Files') else - self.display_name + display_name end else - self.display_name + display_name end else - re = Regexp.new("#{self.asset_code} - ") - self.display_name.nil? ? "" : self.display_name.gsub(re, "") + re = Regexp.new("#{asset_code} - ") + display_name.nil? ? "" : display_name.gsub(re, "") end end @@ -185,7 +185,7 @@ def asset end def asset_class_name - name = self.asset.class.name.underscore if self.asset + name = asset.class.name.underscore if asset name = "Quiz" if name == "Quizzes::Quiz" name end @@ -209,7 +209,7 @@ def self.get_correct_context(context, accessed_asset) def self.log(user, context, accessed_asset) return unless user && accessed_asset[:code] - correct_context = self.get_correct_context(context, accessed_asset) + correct_context = get_correct_context(context, accessed_asset) return unless correct_context && Context::CONTEXT_TYPES.include?(correct_context.class_name.to_sym) GuardRail.activate(:secondary) do @@ -232,7 +232,7 @@ def log(kontext, accessed) infer_defaults infer_root_account_id(accessed[:asset_for_root_account_id]) - if self.class.use_log_compaction_for_views? && self.eligible_for_log_path? + if self.class.use_log_compaction_for_views? && eligible_for_log_path? # Since this is JUST a view bump, we'll write it to the # view log and let periodic jobs compact them later # (this is intentionally trading off more latency for less I/O pressure) @@ -248,8 +248,8 @@ def eligible_for_log_path? # view count updates happen a LOT though, so if the setting is # configured such that we're allowed to use the log path, check # if this set of changes is "just" a view update. - change_hash = self.changes_to_save - updated_key_set = self.changes_to_save.keys.to_set + change_hash = changes_to_save + updated_key_set = changes_to_save.keys.to_set return false unless updated_key_set.include?('view_score') return false unless (updated_key_set - Set.new(['updated_at', 'last_access', 'view_score'])).empty? @@ -268,13 +268,13 @@ def log_action(level) increment(:view_score) if %w[view participate].include?(level) increment(:participate_score) if %w[participate submit].include?(level) - if self.action_level != 'participate' + if action_level != 'participate' self.action_level = (level == 'submit') ? 'participate' : level end end def self.use_log_compaction_for_views? - self.view_counting_method.to_s == "log" + view_counting_method.to_s == "log" end def self.view_counting_method @@ -292,7 +292,7 @@ def corrected_view_score deductible_points = 0 if 'quizzes' == self.asset_group_code - deductible_points = self.participate_score || 0 + deductible_points = participate_score || 0 end self.view_score ||= 0 @@ -332,7 +332,7 @@ def readable_category private def increment(attribute) - incremented_value = (self.send(attribute) || 0) + 1 - self.send("#{attribute}=", incremented_value) + incremented_value = (send(attribute) || 0) + 1 + send("#{attribute}=", incremented_value) end end diff --git a/app/models/asset_user_access_log.rb b/app/models/asset_user_access_log.rb index eabeede015efa..208f75d953887 100644 --- a/app/models/asset_user_access_log.rb +++ b/app/models/asset_user_access_log.rb @@ -163,7 +163,7 @@ def self.plugin_setting # We can remove them entirely, along with the postgres read/write # code paths, once that transition is complete. def self.write_to_message_bus?(shard) - self.channel_config(shard).fetch("pulsar_writes_enabled", false) + channel_config(shard).fetch("pulsar_writes_enabled", false) end # TODO: these config predicate methods should only exist while we are @@ -171,7 +171,7 @@ def self.write_to_message_bus?(shard) # We can remove them entirely, along with the postgres read/write # code paths, once that transition is complete. def self.write_to_db_partition?(shard) - self.channel_config(shard).fetch("db_writes_enabled", true) + channel_config(shard).fetch("db_writes_enabled", true) end # TODO: these config predicate methods should only exist while we are @@ -179,7 +179,7 @@ def self.write_to_db_partition?(shard) # We can remove them entirely, along with the postgres read/write # code paths, once that transition is complete. def self.read_from_message_bus?(shard) - self.channel_config(shard).fetch("pulsar_reads_enabled", false) + channel_config(shard).fetch("pulsar_reads_enabled", false) end # This config map is intended to be used during the transition @@ -263,14 +263,14 @@ def self.update_metadatum(compaction_state) def self.compact ps = plugin_setting if ps.nil? || ps.settings[:write_path] != "log" - return self.log_message("PluginSetting configured OFF, aborting") + return log_message("PluginSetting configured OFF, aborting") end shard = ::Switchman::Shard.current - caught_up = if self.read_from_message_bus?(shard) - self.message_bus_compact + caught_up = if read_from_message_bus?(shard) + message_bus_compact else - self.postgres_compact + postgres_compact end # it's ok if we didn't complete, we time the job out so that # for things that need to move or hold jobs they don't have to @@ -289,9 +289,9 @@ def self.compact def self.message_bus_compact Bundler.require(:pulsar) # makes sure we can capture Pulsar errors # Step 0) load iterator state and settings - compaction_state = self.metadatum_payload + compaction_state = metadatum_payload compaction_start = Time.now.utc - mb_settings = self.compaction_settings + mb_settings = compaction_settings log_batch_size = mb_settings[:log_batch_size] max_compaction_time = mb_settings[:max_compaction_time] receive_timeout = mb_settings[:receive_timeout] @@ -332,7 +332,7 @@ def self.message_bus_compact # the earliest message in storage on that topic, but we # can use the compaction state from metadatum_payload to # skip forward until we find messages we haven't processed. - topic = self.message_bus_topic_name(root_account) + topic = message_bus_topic_name(root_account) # we explicitly close this consumer at the end of processing, so we don't want # a cached consumer. consumer = nil @@ -392,7 +392,7 @@ def self.message_bus_compact while continue_consuming_from_bus consumed_count = 0 skip_count = 0 - self.log_message("Pulling messages from bus for RA #{root_account_id}...") + log_message("Pulling messages from bus for RA #{root_account_id}...") # 4) subscribe to start receiving messages while !caught_up_for_account && (consumed_count < log_batch_size) message = nil @@ -406,7 +406,7 @@ def self.message_bus_compact end message_hash = JSON.parse(message.data).with_indifferent_access unless message_hash.key?(:asset_user_access_id) - self.log_message("MALFORMED MESSAGE, skipping: #{message.data}") + log_message("MALFORMED MESSAGE, skipping: #{message.data}") next end # 5) check each entry against the metadata index to see if it should be processed before adding to datastructure @@ -470,7 +470,7 @@ def self.message_bus_compact else skip_count += 1 if skip_count % 1000 == 0 - self.log_message("...Skipped #{skip_count} so far...") + log_message("...Skipped #{skip_count} so far...") end end # 8) loop on subscription until the datastructure is filled or the receive operation times out @@ -496,16 +496,16 @@ def self.message_bus_compact # state are updated in lock step, so if we fail we should re-aggregate from the same point. AssetUserAccess.transaction do unless aggregation_results.empty? - self.log_message("message bus batch updating (sometimes these queries don't get logged)...") - AssetUserAccess.connection.execute(self.compaction_sql(aggregation_results)) + log_message("message bus batch updating (sometimes these queries don't get logged)...") + AssetUserAccess.connection.execute(compaction_sql(aggregation_results)) end # Here we want to write the iteration state into the database # so that we don't double count rows later. The next time the job # runs it can pick up at this point and only count rows that haven't yet been counted. compaction_state[:temp_root_account_max_log_ids][root_account_id.to_s] = root_account_postgres_iterator_state compaction_state[:pulsar_partition_iterators][root_account_id.to_s] = new_message_bus_iterator_state - self.update_metadatum(compaction_state) - self.log_message("...batch update complete") + update_metadatum(compaction_state) + log_message("...batch update complete") end end @@ -608,7 +608,7 @@ def self.postgres_compact unless yesterday_model.take(1).empty? yesterday_completed = compact_partition(yesterday_ts) ps.reload - compaction_state = self.metadatum_payload + compaction_state = metadatum_payload max_yesterday_id = compaction_state[:max_log_ids][yesterday_ts.wday] if yesterday_completed && max_yesterday_id >= yesterday_model.maximum(:id) # we have now compacted all the writes from the previous day. @@ -625,7 +625,7 @@ def self.postgres_compact yesterday_model.connection.truncate(yesterday_model.table_name) end compaction_state[:max_log_ids][yesterday_ts.wday] = 0 - self.update_metadatum(compaction_state) + update_metadatum(compaction_state) end end end @@ -670,7 +670,7 @@ def self.compact_partition(ts) # We'd expect them to usually be 0 because we reset the value after truncating the partition # (defends against sequences being reset to the "highest" record in a table and then # deciding we already chomped these logs). - compaction_state = self.metadatum_payload + compaction_state = metadatum_payload GuardRail.activate(:secondary) do # select the boundaries of the log segment we're going to iterate. @@ -693,7 +693,7 @@ def self.compact_partition(ts) use_pulsar_ripcord_iterators = !root_account_max_ids_map.empty? log_id_bookmark = [(partition_lower_bound - 1), state_max_log_ids[ts.wday]].max while log_id_bookmark < partition_upper_bound - self.log_message("processing #{log_id_bookmark} from #{partition_upper_bound}") + log_message("processing #{log_id_bookmark} from #{partition_upper_bound}") # maybe we won't need this, but if we need to slow down throughput and don't want to hold # the jobs, increasing this setting value could tradeoff throughput for latency # slowly. We load in INSIDE the loop so that SIGHUPS can get recognized @@ -722,14 +722,14 @@ def self.compact_partition(ts) new_iterator_pos = log_segment_aggregation.map { |r| r["max_id"] }.max GuardRail.activate(:primary) do partition_model.transaction do - self.log_message("batch updating (sometimes these queries don't get logged)...") + log_message("batch updating (sometimes these queries don't get logged)...") partition_model.connection.execute(update_query) - self.log_message("...batch update complete") + log_message("...batch update complete") # Here we want to write the iteration state into the database # so that we don't double count rows later. The next time the job # runs it can pick up at this point and only count rows that haven't yet been counted. compaction_state[:max_log_ids][ts.wday] = new_iterator_pos - self.update_metadatum(compaction_state) + update_metadatum(compaction_state) end end log_id_bookmark = new_iterator_pos @@ -757,7 +757,7 @@ def self.compact_partition(ts) new_bookmark_id = next_id - 1 GuardRail.activate(:primary) do compaction_state[:max_log_ids][ts.wday] = new_bookmark_id - self.update_metadatum(compaction_state) + update_metadatum(compaction_state) end log_id_bookmark = new_bookmark_id end @@ -776,7 +776,7 @@ def self.compact_partition(ts) # iteration state from the pulsar processing anymore since we've moved # the global iterator past those positions, and we can null out that state compaction_state[:temp_root_account_max_log_ids] = {} - self.update_metadatum(compaction_state) + update_metadatum(compaction_state) end true # to indicate we didn't bail end diff --git a/app/models/assignment.rb b/app/models/assignment.rb index 8a05adc7db3a3..b4a71c421d5a4 100644 --- a/app/models/assignment.rb +++ b/app/models/assignment.rb @@ -205,8 +205,8 @@ def context_code end def positive_points_possible? - return if self.points_possible.to_i >= 0 - return unless self.points_possible_changed? + return if points_possible.to_i >= 0 + return unless points_possible_changed? errors.add( :points_possible, @@ -218,8 +218,8 @@ def positive_points_possible? end def reasonable_points_possible? - return if self.points_possible.to_i < 1000000000 - return unless self.points_possible_changed? + return if points_possible.to_i < 1000000000 + return unless points_possible_changed? errors.add( :points_possible, @@ -230,10 +230,10 @@ def reasonable_points_possible? end def get_potentially_conflicting_titles(title_base) - assignment_titles = Assignment.active.for_course(self.context_id) + assignment_titles = Assignment.active.for_course(context_id) .starting_with_title(title_base).pluck("title").to_set - wiki_titles = if self.wiki_page - self.wiki_page.get_potentially_conflicting_titles(title_base) + wiki_titles = if wiki_page + wiki_page.get_potentially_conflicting_titles(title_base) else [].to_set end @@ -259,7 +259,7 @@ def duplicate(opts = {}) raise "This assignment can't be duplicated" unless can_duplicate? # Don't clone a new record - return self if self.new_record? + return self if new_record? default_opts = { :duplicate_wiki_page => true, @@ -270,7 +270,7 @@ def duplicate(opts = {}) } opts_with_default = default_opts.merge(opts) - result = self.clone + result = clone result.all_submissions.clear result.attachments.clear result.ignores.clear @@ -285,35 +285,35 @@ def duplicate(opts = {}) # override later. Just helps to avoid duplicate positions. result.position = Assignment.active.where(assignment_group: assignment_group).maximum(:position) + 1 result.title = - opts_with_default[:copy_title] || get_copy_title(self, t("Copy"), self.title) + opts_with_default[:copy_title] || get_copy_title(self, t("Copy"), title) - if self.wiki_page && opts_with_default[:duplicate_wiki_page] - result.wiki_page = self.wiki_page.duplicate({ - :duplicate_assignment => false, - :copy_title => result.title - }) + if wiki_page && opts_with_default[:duplicate_wiki_page] + result.wiki_page = wiki_page.duplicate({ + :duplicate_assignment => false, + :copy_title => result.title + }) end - if self.discussion_topic && opts_with_default[:duplicate_discussion_topic] - result.discussion_topic = self.discussion_topic.duplicate({ - :duplicate_assignment => false, - :copy_title => result.title, - :user => opts_with_default[:user] - }) + if discussion_topic && opts_with_default[:duplicate_discussion_topic] + result.discussion_topic = discussion_topic.duplicate({ + :duplicate_assignment => false, + :copy_title => result.title, + :user => opts_with_default[:user] + }) end result.discussion_topic&.assignment = result - if self.assignment_configuration_tool_lookups.present? && opts_with_default[:duplicate_plagiarism_tool_association] + if assignment_configuration_tool_lookups.present? && opts_with_default[:duplicate_plagiarism_tool_association] result.assignment_configuration_tool_lookups = [ - self.assignment_configuration_tool_lookups.first.dup + assignment_configuration_tool_lookups.first.dup ] end # Learning outcome alignments seem to get copied magically, possibly # through the rubric if active_rubric_association? - result.rubric_association = self.rubric_association.clone + result.rubric_association = rubric_association.clone result.rubric_association.skip_updating_points_possible = true end @@ -412,8 +412,8 @@ def max_name_length def secure_params body = {} - body[:lti_assignment_id] = self.lti_context_id || SecureRandom.uuid - body[:lti_assignment_description] = self.lti_safe_description + body[:lti_assignment_id] = lti_context_id || SecureRandom.uuid + body[:lti_assignment_description] = lti_safe_description Canvas::Security.create_jwt(body) end @@ -429,7 +429,7 @@ def provisional_grades_exist? return false unless moderated_grading? || moderated_grading_changed? ModeratedGrading::ProvisionalGrade - .where(submission_id: self.submissions.having_submission.select(:id)) + .where(submission_id: submissions.having_submission.select(:id)) .where.not(score: nil).exists? end @@ -507,7 +507,7 @@ def moderation_setting_ok? ].freeze def external_tool? - self.submission_types == 'external_tool' + submission_types == 'external_tool' end validates :context_id, :context_type, :workflow_state, presence: true @@ -521,14 +521,14 @@ def external_tool? acts_as_list :scope => :assignment_group simply_versioned :keep => 5 sanitize_field :description, CanvasSanitize::SANITIZE - copy_authorized_links(:description) { [self.context, nil] } + copy_authorized_links(:description) { [context, nil] } def root_account context&.root_account end def name - self.title + title end def name=(val) @@ -562,7 +562,7 @@ def allowed_extensions=(new_value) before_destroy :delete_observer_alerts def delete_observer_alerts - until self.observer_alerts.limit(1_000).delete_all < 1_000; end + until observer_alerts.limit(1_000).delete_all < 1_000; end end before_create :set_root_account_id, :set_muted @@ -693,7 +693,7 @@ def schedule_do_auto_peer_review_job_if_automatic_peer_review run_at = 1.minute.from_now if run_at < 1.minute.from_now # delay immediate run in case associated objects are still being saved delay(run_at: run_at, on_conflict: :overwrite, - singleton: Shard.birth.activate { "assignment:auto_peer_review:#{self.id}" }) + singleton: Shard.birth.activate { "assignment:auto_peer_review:#{id}" }) .do_auto_peer_review end @@ -711,7 +711,7 @@ def touch_assignment_group if saved_change_to_assignment_group_id? && assignment_group_id_before_last_save.present? AssignmentGroup.where(id: assignment_group_id_before_last_save).update_all(updated_at: Time.zone.now.utc) end - AssignmentGroup.where(:id => self.assignment_group_id).update_all(:updated_at => Time.zone.now.utc) if self.assignment_group_id + AssignmentGroup.where(:id => assignment_group_id).update_all(:updated_at => Time.zone.now.utc) if assignment_group_id true end @@ -733,7 +733,7 @@ def update_student_submissions(updating_user) s.with_versioning(:explicit => true) { s.save! } end - unless self.saved_by == :migration + unless saved_by == :migration context.recompute_student_scores end end @@ -778,9 +778,9 @@ def needs_to_recompute_grade? def update_grades_if_details_changed if needs_to_recompute_grade? - unless self.saved_by == :migration + unless saved_by == :migration Rails.logger.debug "GRADES: recalculating because assignment #{global_id} changed. (#{saved_changes.inspect})" - self.class.connection.after_transaction_commit { self.context.recompute_student_scores } + self.class.connection.after_transaction_commit { context.recompute_student_scores } end end true @@ -788,7 +788,7 @@ def update_grades_if_details_changed private :update_grades_if_details_changed def update_grading_period_grades - return true unless saved_change_to_due_at? && !saved_change_to_id? && context.grading_periods? && self.saved_by != :migration + return true unless saved_change_to_due_at? && !saved_change_to_id? && context.grading_periods? && saved_by != :migration grading_period_was = GradingPeriod.for_date_in_course(date: due_at_before_last_save, course: context) grading_period = GradingPeriod.for_date_in_course(date: due_at, course: context) @@ -814,24 +814,24 @@ def update_grading_period_grades private :update_grading_period_grades def create_in_turnitin - return false unless self.context.turnitin_settings - return true if self.turnitin_settings[:current] + return false unless context.turnitin_settings + return true if turnitin_settings[:current] - turnitin = Turnitin::Client.new(*self.context.turnitin_settings) - res = turnitin.createOrUpdateAssignment(self, self.turnitin_settings) + turnitin = Turnitin::Client.new(*context.turnitin_settings) + res = turnitin.createOrUpdateAssignment(self, turnitin_settings) # make sure the defaults get serialized self.turnitin_settings = turnitin_settings if res[:assignment_id] - self.turnitin_settings[:created] = true - self.turnitin_settings[:current] = true - self.turnitin_settings.delete(:error) + turnitin_settings[:created] = true + turnitin_settings[:current] = true + turnitin_settings.delete(:error) else - self.turnitin_settings[:error] = res + turnitin_settings[:error] = res end - self.save - self.turnitin_settings[:current] + save + turnitin_settings[:current] end def turnitin_settings(settings = nil) @@ -858,7 +858,7 @@ def turnitin_settings=(settings) end unless settings.blank? [:created, :error].each do |key| - settings[key] = self.turnitin_settings[key] if self.turnitin_settings[key] + settings[key] = turnitin_settings[key] if turnitin_settings[key] end end write_attribute :turnitin_settings, settings @@ -866,35 +866,35 @@ def turnitin_settings=(settings) def create_in_vericite return false unless Canvas::Plugin.find(:vericite).try(:enabled?) - return true if self.turnitin_settings[:current] && self.turnitin_settings[:vericite] + return true if turnitin_settings[:current] && turnitin_settings[:vericite] vericite = VeriCite::Client.new - res = vericite.createOrUpdateAssignment(self, self.turnitin_settings) + res = vericite.createOrUpdateAssignment(self, turnitin_settings) # make sure the defaults get serialized self.turnitin_settings = turnitin_settings if res[:assignment_id] - self.turnitin_settings[:created] = true - self.turnitin_settings[:current] = true - self.turnitin_settings[:vericite] = true - self.turnitin_settings.delete(:error) + turnitin_settings[:created] = true + turnitin_settings[:current] = true + turnitin_settings[:vericite] = true + turnitin_settings.delete(:error) else - self.turnitin_settings[:error] = res + turnitin_settings[:error] = res end - self.save - self.turnitin_settings[:current] + save + turnitin_settings[:current] end def vericite_settings - self.turnitin_settings(VeriCite::Client.default_assignment_vericite_settings) + turnitin_settings(VeriCite::Client.default_assignment_vericite_settings) end def vericite_settings=(settings) settings = VeriCite::Client.normalize_assignment_vericite_settings(settings) unless settings.blank? [:created, :error].each do |key| - settings[key] = self.turnitin_settings[key] if self.turnitin_settings[key] + settings[key] = turnitin_settings[key] if turnitin_settings[key] end end write_attribute :turnitin_settings, settings @@ -938,14 +938,14 @@ def ensure_post_to_sis_valid private :ensure_post_to_sis_valid def default_values - raise "Assignments can only be assigned to Course records" if self.context_type && self.context_type != "Course" + raise "Assignments can only be assigned to Course records" if context_type && context_type != "Course" - self.title ||= (self.assignment_group.default_assignment_name rescue nil) || "Assignment" + self.title ||= (assignment_group.default_assignment_name rescue nil) || "Assignment" - self.infer_all_day - self.position = self.position_was if self.will_save_change_to_position? && self.position.nil? # don't allow setting to nil + infer_all_day + self.position = position_was if will_save_change_to_position? && position.nil? # don't allow setting to nil - if !self.assignment_group || (self.assignment_group.deleted? && !self.deleted?) + if !assignment_group || (assignment_group.deleted? && !deleted?) ensure_assignment_group(false) end self.submission_types ||= "none" @@ -965,8 +965,8 @@ def default_values def ensure_assignment_group(do_save = true) return if assignment_group_id - self.context.require_assignment_group - self.assignment_group = self.context.assignment_groups.active.first + context.require_assignment_group + self.assignment_group = context.assignment_groups.active.first if do_save GuardRail.activate(:primary) { save! } end @@ -977,7 +977,7 @@ def attendance? end def due_date - self.all_day ? self.all_day_date : self.due_at + all_day ? all_day_date : due_at end def delete_empty_abandoned_children @@ -999,7 +999,7 @@ def update_submissions_later def update_submissions @updated_submissions ||= [] Submission.suspend_callbacks(:update_assignment, :touch_graders) do - self.submissions.find_each do |submission| + submissions.find_each do |submission| @updated_submissions << submission submission.save! end @@ -1010,37 +1010,37 @@ def update_submissions def update_submittable # If we're updating the assignment's muted status as part of posting # grades, don't bother doing this - return true if self.deleted? || grade_posting_in_progress + return true if deleted? || grade_posting_in_progress if self.submission_types == "online_quiz" && @saved_by != :quiz - quiz = Quizzes::Quiz.where(assignment_id: self).first || self.context.quizzes.build - quiz.assignment_id = self.id + quiz = Quizzes::Quiz.where(assignment_id: self).first || context.quizzes.build + quiz.assignment_id = id quiz.title = self.title - quiz.description = self.description - quiz.due_at = self.due_at - quiz.unlock_at = self.unlock_at - quiz.lock_at = self.lock_at - quiz.points_possible = self.points_possible - quiz.assignment_group_id = self.assignment_group_id + quiz.description = description + quiz.due_at = due_at + quiz.unlock_at = unlock_at + quiz.lock_at = lock_at + quiz.points_possible = points_possible + quiz.assignment_group_id = assignment_group_id quiz.workflow_state = 'created' if quiz.deleted? quiz.saved_by = :assignment quiz.workflow_state = published? ? 'available' : 'unpublished' quiz.save if quiz.changed? elsif self.submission_types == "discussion_topic" && @saved_by != :discussion_topic - topic = self.discussion_topic || self.context.discussion_topics.build(:user => @updating_user) - topic.message = self.description + topic = discussion_topic || context.discussion_topics.build(:user => @updating_user) + topic.message = description save_submittable(topic) self.discussion_topic = topic - elsif self.context.feature_enabled?(:conditional_release) && + elsif context.feature_enabled?(:conditional_release) && self.submission_types == "wiki_page" && @saved_by != :wiki_page - page = self.wiki_page || self.context.wiki_pages.build(:user => @updating_user) + page = wiki_page || context.wiki_pages.build(:user => @updating_user) save_submittable(page) self.wiki_page = page end end def save_submittable(submittable) - submittable.assignment_id = self.id + submittable.assignment_id = id submittable.title = self.title submittable.saved_by = :assignment submittable.updated_at = Time.zone.now @@ -1051,13 +1051,13 @@ def save_submittable(submittable) protected :save_submittable def update_grading_standard - self.grading_standard&.save! + grading_standard&.save! end def all_context_module_tags all_tags = context_module_tags.to_a each_submission_type do |submission, _, short_type| - all_tags.concat(submission.context_module_tags) if self.send("#{short_type}?") + all_tags.concat(submission.context_module_tags) if send("#{short_type}?") end all_tags end @@ -1170,14 +1170,14 @@ def update_line_items # and creates results like they are created in the AGS Scores API. # It ignores any previous submission versions in favor of the most recent. def create_results_from_prior_grades(line_item) - self.submissions.where.not(score: nil).each do |sub| + submissions.where.not(score: nil).each do |sub| line_item.results.create!( submission: sub, user: sub.user, created_at: Time.zone.now, updated_at: sub.graded_at, result_score: sub.score, - result_maximum: self.points_possible || 0, + result_maximum: points_possible || 0, extensions: { Lti::Result::AGS_EXT_SUBMISSION => { submitted_at: sub.submitted_at } } @@ -1216,7 +1216,7 @@ def do_notifications!(prior_version = nil, notify = false) # TODO: this will blow up if the group_category string is set on the # previous version, because it gets confused between the db string field # and the association. one more reason to drop the db column - prior_version ||= self.versions.previous(self.current_version.number).try(:model) + prior_version ||= versions.previous(current_version.number).try(:model) self.notify_of_update = notify || false broadcast_notifications(prior_version || dup) remove_assignment_updated_flag @@ -1328,22 +1328,22 @@ def points_uneditable? def destroy self.workflow_state = 'deleted' ContentTag.delete_for(self) - self.rubric_association.destroy if active_rubric_association? - self.save! + rubric_association.destroy if active_rubric_association? + save! each_submission_type { |submission| submission.destroy if submission && !submission.deleted? } - self.conditional_release_rules.destroy_all - self.conditional_release_associations.destroy_all + conditional_release_rules.destroy_all + conditional_release_associations.destroy_all refresh_course_content_participation_counts - ScheduledSmartAlert.where(context_type: 'Assignment', context_id: self.id).destroy_all - ScheduledSmartAlert.where(context_type: 'AssignmentOverride', context_id: self.assignment_override_ids).destroy_all + ScheduledSmartAlert.where(context_type: 'Assignment', context_id: id).destroy_all + ScheduledSmartAlert.where(context_type: 'AssignmentOverride', context_id: assignment_override_ids).destroy_all end def refresh_course_content_participation_counts - progress = self.context.progresses.build(tag: 'refresh_content_participation_counts') + progress = context.progresses.build(tag: 'refresh_content_participation_counts') progress.save! - progress.process_job(self.context, :refresh_content_participation_counts, + progress.process_job(context, :refresh_content_participation_counts, singleton: "refresh_content_participation_counts:#{context.global_id}") end @@ -1352,8 +1352,8 @@ def time_zone_edited end def restore(from = nil) - self.workflow_state = self.has_student_submissions? ? "published" : "unpublished" - self.save + self.workflow_state = has_student_submissions? ? "published" : "unpublished" + save each_submission_type do |submission, _, short_type| submission.restore(:assignment) if from != short_type && submission end @@ -1377,9 +1377,9 @@ def self.participants_with_overridden_due_at(assignments) def students_with_visibility(scope = nil) scope ||= context.all_students.where("enrollments.workflow_state NOT IN ('inactive', 'rejected')") - return scope unless self.differentiated_assignments_applies? + return scope unless differentiated_assignments_applies? - scope.able_to_see_assignment_in_course_with_da(self.id, context.id) + scope.able_to_see_assignment_in_course_with_da(id, context.id) end attr_accessor :saved_by @@ -1401,7 +1401,7 @@ def process_if_quiz delegate :grading_scheme, to: :grading_standard_or_default def infer_grading_type - self.grading_type = nil if self.grading_type.blank? + self.grading_type = nil if grading_type.blank? self.grading_type = "pass_fail" if self.submission_types == "attendance" self.grading_type = "not_graded" if self.submission_types == "wiki_page" self.grading_type ||= "points" @@ -1409,7 +1409,7 @@ def infer_grading_type def score_to_grade_percent(score = 0.0) if points_possible && points_possible > 0 - result = score.to_f / self.points_possible + result = score.to_f / points_possible (result * 100.0).round(2) else # there's not really any reasonable value we can set here -- if the @@ -1437,7 +1437,7 @@ def score_to_grade(score = 0.0, given_grade = nil) end result = passed ? "complete" : "incomplete" when "letter_grade", "gpa_scale" - if self.points_possible.to_f > 0.0 + if points_possible.to_f > 0.0 score = BigDecimal(score.to_s.presence || '0.0') / BigDecimal(points_possible.to_s) result = grading_standard_or_default.score_to_grade((score * 100).to_f) elsif given_grade @@ -1512,34 +1512,34 @@ def uses_grading_standard def infer_times # set the time to 11:59 pm in the creator's time zone, if none given - self.due_at = CanvasTime.fancy_midnight(self.due_at) if will_save_change_to_due_at? - self.lock_at = CanvasTime.fancy_midnight(self.lock_at) if will_save_change_to_lock_at? + self.due_at = CanvasTime.fancy_midnight(due_at) if will_save_change_to_due_at? + self.lock_at = CanvasTime.fancy_midnight(lock_at) if will_save_change_to_lock_at? end def infer_all_day(tz = nil) # make the comparison to "fancy midnight" and the date-part extraction in # the time zone that was active during editing - time_zone = tz || (ActiveSupport::TimeZone.new(self.time_zone_edited) rescue nil) || Time.zone + time_zone = tz || (ActiveSupport::TimeZone.new(time_zone_edited) rescue nil) || Time.zone self.all_day, self.all_day_date = Assignment.all_day_interpretation( - :due_at => self.due_at ? self.due_at.in_time_zone(time_zone) : nil, - :due_at_was => self.due_at_was, - :all_day_was => self.all_day_was, - :all_day_date_was => self.all_day_date_was + :due_at => due_at ? due_at.in_time_zone(time_zone) : nil, + :due_at_was => due_at_was, + :all_day_was => all_day_was, + :all_day_date_was => all_day_date_was ) end def to_atom(opts = {}) extend ApplicationHelper - author_name = self.context.present? ? self.context.name : t('atom_no_author', "No Author") + author_name = context.present? ? context.name : t('atom_no_author', "No Author") Atom::Entry.new do |entry| entry.title = t(:feed_entry_title, "Assignment: %{assignment}", :assignment => self.title) unless opts[:include_context] - entry.title = t(:feed_entry_title_with_course, "Assignment, %{course}: %{assignment}", :assignment => self.title, :course => self.context.name) if opts[:include_context] - entry.updated = self.updated_at.utc - entry.published = self.created_at.utc - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime('%Y-%m-%d')}:/assignments/#{self.feed_code}_#{self.due_at.strftime('%Y-%m-%d-%H-%M') rescue 'none'}" - entry.content = Atom::Content::Html.new(before_label(:due, "Due") + " #{datetime_string(self.due_at, :due_date)}
#{self.description}

+ entry.title = t(:feed_entry_title_with_course, "Assignment, %{course}: %{assignment}", :assignment => self.title, :course => context.name) if opts[:include_context] + entry.updated = updated_at.utc + entry.published = created_at.utc + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime('%Y-%m-%d')}:/assignments/#{feed_code}_#{due_at.strftime('%Y-%m-%d-%H-%M') rescue 'none'}" + entry.content = Atom::Content::Html.new(before_label(:due, "Due") + " #{datetime_string(due_at, :due_date)}
#{description}

- #{self.description} + #{description}
") entry.links << Atom::Link.new(:rel => 'alternate', :href => direct_link) @@ -1556,7 +1556,7 @@ def end_at end def direct_link - "http://#{HostUrl.context_host(self.context)}/#{context_url_prefix}/assignments/#{self.id}" + "http://#{HostUrl.context_host(context)}/#{context_url_prefix}/assignments/#{id}" end def context_prefix @@ -1577,7 +1577,7 @@ def include_description?(user, lock_info = nil) end def all_day - read_attribute(:all_day) || (self.new_record? && !!self.due_at && (self.due_at.strftime("%H:%M") == '23:59' || self.due_at.strftime("%H:%M") == '00:00')) + read_attribute(:all_day) || (new_record? && !!due_at && (due_at.strftime("%H:%M") == '23:59' || due_at.strftime("%H:%M") == '00:00')) end def self.preload_context_module_tags(assignments, include_context_modules: false) @@ -1625,22 +1625,22 @@ def self.preload_unposted_anonymous_submissions(assignments) end def touch_on_unlock_if_necessary - if self.unlock_at && Time.zone.now < self.unlock_at && (Time.zone.now + 1.hour) > self.unlock_at + if unlock_at && Time.zone.now < unlock_at && (Time.zone.now + 1.hour) > unlock_at GuardRail.activate(:primary) do # Because of assignemnt overrides, an assignment can have the same global id but # a different unlock_at time, so include that in the singleton key so that different # unlock_at times are properly handled. - singleton = "touch_on_unlock_assignment_#{self.global_id}_#{self.unlock_at}" - delay(run_at: self.unlock_at, singleton: singleton).touch_assignment_and_submittable + singleton = "touch_on_unlock_assignment_#{global_id}_#{unlock_at}" + delay(run_at: unlock_at, singleton: singleton).touch_assignment_and_submittable end end end def touch_assignment_and_submittable - self.touch - self.submittable_object&.touch - if self.submittable_object.is_a?(DiscussionTopic) && self.submittable_object.root_topic? - self.submittable_object.child_topics.touch_all + touch + submittable_object&.touch + if submittable_object.is_a?(DiscussionTopic) && submittable_object.root_topic? + submittable_object.child_topics.touch_all end end @@ -1649,16 +1649,16 @@ def low_level_locked_for?(user, opts = {}) RequestCache.cache(locked_request_cache_key(user)) do locked = false - assignment_for_user = self.overridden_for(user) + assignment_for_user = overridden_for(user) if assignment_for_user.unlock_at && assignment_for_user.unlock_at > Time.zone.now locked = { object: assignment_for_user, unlock_at: assignment_for_user.unlock_at } - elsif self.could_be_locked && (item = locked_by_module_item?(user, opts)) + elsif could_be_locked && (item = locked_by_module_item?(user, opts)) locked = { object: self, module: item.context_module } elsif assignment_for_user.lock_at && assignment_for_user.lock_at < Time.zone.now locked = { object: assignment_for_user, lock_at: assignment_for_user.lock_at, can_view: true } else each_submission_type do |submission, _, short_type| - next unless self.send("#{short_type}?") + next unless send("#{short_type}?") if (submission_locked = submission.low_level_locked_for?(user, opts.merge(:skip_assignment => true))) locked = submission_locked @@ -1703,20 +1703,20 @@ def submittable_type? def submittable_object case self.submission_types when 'online_quiz' - self.quiz + quiz when 'discussion_topic' - self.discussion_topic + discussion_topic when 'wiki_page' - self.wiki_page + wiki_page end end def each_submission_type if block_given? submittable_types = %i[discussion_topic quiz] - submittable_types << :wiki_page if self.context.try(:feature_enabled?, :conditional_release) + submittable_types << :wiki_page if context.try(:feature_enabled?, :conditional_release) submittable_types.each do |asg_type| - submittable = self.send(asg_type) + submittable = send(asg_type) yield submittable, Assignment.get_submission_type(asg_type), asg_type end end @@ -1741,12 +1741,12 @@ def submitted_count return read_attribute(:submitted_count).to_i if read_attribute(:submitted_count) Rails.cache.fetch(['submitted_count', self].cache_key) do - self.submissions.having_submission.count + submissions.having_submission.count end end set_policy do - given { |user, session| self.context.grants_right?(user, session, :read) && self.published? } + given { |user, session| context.grants_right?(user, session, :read) && published? } can :read and can :read_own_submission given { |user, session| @@ -1765,10 +1765,10 @@ def submitted_count end can :attach_submission_comment_files - given { |user, session| self.context.grants_right?(user, session, :read_as_admin) } + given { |user, session| context.grants_right?(user, session, :read_as_admin) } can :read - given { |user, session| self.context.grants_right?(user, session, :manage_grades) } + given { |user, session| context.grants_right?(user, session, :manage_grades) } can :grade and can :attach_submission_comment_files and can :manage_files_add and @@ -1776,32 +1776,32 @@ def submitted_count can :manage_files_delete given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments) + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments) end can :create and can :read given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_add) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_add) end can :create and can :read - given { |user, session| self.user_can_update?(user, session) } + given { |user, session| user_can_update?(user, session) } can :update given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments) && - (self.context.account_membership_allows(user) || + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments) && + (context.account_membership_allows(user) || !in_closed_grading_period?) end can :delete given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_delete) && - (self.context.account_membership_allows(user) || + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_delete) && + (context.account_membership_allows(user) || !in_closed_grading_period?) end can :delete @@ -1818,13 +1818,13 @@ def user_can_update?(user, session = nil) def user_can_read_grades?(user, session = nil) RequestCache.cache('user_can_read_grades', self, user, session) do - self.context.grants_right?(user, session, :view_all_grades) || - (self.published? && self.context.grants_right?(user, session, :manage_grades)) + context.grants_right?(user, session, :view_all_grades) || + (published? && context.grants_right?(user, session, :manage_grades)) end end def filter_attributes_for_user(hash, user, _session) - if (lock_info = self.locked_for?(user, :check_policies => true)) + if (lock_info = locked_for?(user, :check_policies => true)) hash.delete('description') unless include_description?(user, lock_info) hash['lock_info'] = lock_info end @@ -1845,7 +1845,7 @@ def participants_with_visibility(opts = {}) users += applicable_students if opts[:include_observers] - users += User.observing_students_in_course(applicable_students.map(&:id), self.context_id) + users += User.observing_students_in_course(applicable_students.map(&:id), context_id) users += User.observing_full_course(context.id) end @@ -1873,7 +1873,7 @@ def group_students(student) students = if group group.users .joins(:enrollments) - .where(:enrollments => { :course_id => self.context }) + .where(:enrollments => { :course_id => context }) .merge(Course.instance_exec(&Course.reflections['admin_visible_student_enrollments'].scope).only(:where)) .order("users.id") # this helps with preventing deadlock with other things that touch lots of users .distinct @@ -1886,9 +1886,9 @@ def group_students(student) end def multiple_module_actions(student_ids, action, points = nil) - students = self.context.students.where(id: student_ids) + students = context.students.where(id: student_ids) students.each do |user| - self.context_module_action(user, action, points) + context_module_action(user, action, points) end end @@ -1897,17 +1897,17 @@ def submission_for_student(user) end def submission_for_student_id(user_id) - self.all_submissions.where(user_id: user_id).first_or_initialize + all_submissions.where(user_id: user_id).first_or_initialize end def compute_grade_and_score(grade, score) grade = nil if grade == '' if grade - score = self.grade_to_score(grade) + score = grade_to_score(grade) end if score - grade = self.score_to_grade(score, grade) + grade = score_to_grade(score, grade) end [grade, score] end @@ -1917,7 +1917,7 @@ def grade_student(original_student, opts = {}) unless context.includes_user?(original_student, context.admin_visible_student_enrollments) # allows inactive users to be graded raise GradeError, "Student must be enrolled in the course as a student to be graded" end - raise GradeError, "Grader must be enrolled as a course admin" if opts[:grader] && !self.context.grants_right?(opts[:grader], :manage_grades) + raise GradeError, "Grader must be enrolled as a course admin" if opts[:grader] && !context.grants_right?(opts[:grader], :manage_grades) opts[:excused] = Canvas::Plugin.value_to_boolean(opts.delete(:excuse)) if opts.key? :excuse raise GradeError, "Cannot simultaneously grade and excuse an assignment" if opts[:excused] && (opts[:grade] || opts[:score]) @@ -1961,7 +1961,7 @@ def tool_settings_tool_name end def tool_settings_tool - self.tool_settings_tools.first + tool_settings_tools.first end def tool_settings_tool=(tool) @@ -2095,7 +2095,7 @@ def find_or_create_submission(user) end def find_or_create_submissions(students, relation = nil) - submissions = self.all_submissions.where(user_id: students) + submissions = all_submissions.where(user_id: students) submissions = submissions.merge(relation) if relation submissions_hash = submissions.to_a.index_by(&:user_id) submissions = [] @@ -2110,7 +2110,7 @@ def find_or_create_submissions(students, relation = nil) submission.without_versioning(&:save) if submission.changed? end rescue ActiveRecord::RecordNotUnique - submission = self.all_submissions.where(user_id: student).first + submission = all_submissions.where(user_id: student).first raise unless submission submission.assignment = self @@ -2128,10 +2128,10 @@ def find_or_create_submissions(students, relation = nil) end def find_asset_for_assessment(association, user_or_user_id, opts = {}) - user = user_or_user_id.is_a?(User) ? user_or_user_id : self.context.users.where(id: user_or_user_id).first + user = user_or_user_id.is_a?(User) ? user_or_user_id : context.users.where(id: user_or_user_id).first if association.purpose == "grading" if user - sub = self.find_or_create_submission(user) + sub = find_or_create_submission(user) if opts[:provisional_grader] [sub.find_or_create_provisional_grade!(opts[:provisional_grader], final: opts[:final]), user] else @@ -2192,7 +2192,7 @@ def update_submission(original_student, opts = {}) def save_comment_to_submission(submission, group, opts, uuid = nil) # Only teachers (those who can manage grades) can have hidden comments unless opts.key?(:hidden) - opts[:hidden] = submission.hide_grade_from_student? && self.context.grants_right?(opts[:author], :manage_grades) + opts[:hidden] = submission.hide_grade_from_student? && context.grants_right?(opts[:author], :manage_grades) end submission.group = group submission.save! if submission.changed? @@ -2217,11 +2217,11 @@ def submit_homework(original_student, opts = {}) if opts[:submission_type] == "student_annotation" raise "Invalid Attachment" if opts[:annotatable_attachment_id].blank? - raise "Invalid submission type" unless self.annotated_document? + raise "Invalid submission type" unless annotated_document? # Prevent the case where a user clicks Submit on a stale tab, expecting # to submit one set of work, only for another set to be submitted # instead. - raise "Invalid Attachment" if opts[:annotatable_attachment_id].to_i != self.annotatable_attachment_id + raise "Invalid Attachment" if opts[:annotatable_attachment_id].to_i != annotatable_attachment_id end # Only allow a few fields to be submitted. Cannot submit the grade of a @@ -2273,7 +2273,7 @@ def submit_homework(original_student, opts = {}) homework.turnitin_data.delete(:webhook_info) end - if self.annotated_document? + if annotated_document? annotation_context = homework.annotation_context(draft: true) end @@ -2324,7 +2324,7 @@ def submission_attributes(opts, group) end def submissions_downloaded? - self.submissions_downloads && self.submissions_downloads > 0 + submissions_downloads && submissions_downloads > 0 end def serializable_hash(opts = {}) @@ -2338,12 +2338,12 @@ def as_json(options = {}) if json['assignment'] # remove anything coming automatically from deprecated db column json['assignment'].delete('group_category') - if self.group_category + if group_category # put back version from association - json['assignment']['group_category'] = self.group_category.name - elsif self.read_attribute('group_category').present? + json['assignment']['group_category'] = group_category.name + elsif read_attribute('group_category').present? # or failing that, version from query - json['assignment']['group_category'] = self.read_attribute('group_category') + json['assignment']['group_category'] = read_attribute('group_category') end if json.dig('assignment', 'rubric_association') && !active_rubric_association? @@ -2367,7 +2367,7 @@ def grades_published? end def sections_with_visibility(user) - return context.active_course_sections unless self.differentiated_assignments_applies? + return context.active_course_sections unless differentiated_assignments_applies? visible_student_ids = visible_students_for_speed_grader(user: user).map(&:id) context.active_course_sections.joins(:student_enrollments) @@ -2436,7 +2436,7 @@ def representatives(user:, includes: [:inactive], group_id: nil, section_id: nil user_ids_who_arent_excused = submissions.reject(&:excused?).map(&:user_id).to_set enrollment_state = - self.context.all_accepted_student_enrollments.pluck(:user_id, :workflow_state).to_h + context.all_accepted_student_enrollments.pluck(:user_id, :workflow_state).to_h # prefer active over inactive, inactive over everything else enrollment_priority = { 'active' => 1, 'inactive' => 2 } @@ -2517,7 +2517,7 @@ def visible_students_for_speed_grader(user:, includes: [:inactive], group_id: ni def visible_rubric_assessments_for(user, opts = {}) return [] unless user && active_rubric_association? - scope = self.rubric_association.rubric_assessments.preload(:assessor) + scope = rubric_association.rubric_assessments.preload(:assessor) if opts[:provisional_grader] scope = scope.for_provisional_grades.where(:assessor_id => user.id) @@ -2525,7 +2525,7 @@ def visible_rubric_assessments_for(user, opts = {}) scope = scope.for_provisional_grades else scope = scope.for_submissions - unless self.rubric_association.grants_any_right?(user, :manage, :view_rubric_assessments) + unless rubric_association.grants_any_right?(user, :manage, :view_rubric_assessments) scope = scope.where(:assessor_id => user.id) end end @@ -2616,7 +2616,7 @@ def submission_reupload_progress end def group_category_name - self.read_attribute(:group_category) + read_attribute(:group_category) end def maintain_group_category_attribute @@ -2624,21 +2624,21 @@ def maintain_group_category_attribute # exists solely for the migration that introduces the GroupCategory model). # this way group_category_name is correct if someone mistakenly uses it # (modulo category renaming in the GroupCategory model). - self.write_attribute(:group_category, self.group_category&.name) + write_attribute(:group_category, group_category&.name) end def has_group_category? - self.group_category_id.present? + group_category_id.present? end def assign_peer_review(reviewer, reviewee) - reviewer_submission = self.find_or_create_submission(reviewer) - reviewee_submission = self.find_or_create_submission(reviewee) + reviewer_submission = find_or_create_submission(reviewer) + reviewee_submission = find_or_create_submission(reviewee) reviewee_submission.assign_assessor(reviewer_submission) end def assign_peer_reviews - return [] unless self.peer_review_count && self.peer_review_count > 0 + return [] unless peer_review_count && peer_review_count > 0 # there could be any conceivable configuration of peer reviews already # assigned when this method is called, since teachers can assign individual @@ -2654,7 +2654,7 @@ def assign_peer_reviews # reviews. peer_review_params[:submissions].sort_by { rand }.each do |submission| existing = submission.assigned_assessments - needed = self.peer_review_count - existing.size + needed = peer_review_count - existing.size next if needed <= 0 # candidate_set is all submissions for the assignment that this @@ -2680,7 +2680,7 @@ def assign_peer_reviews unless @next_auto_peer_review_date self.peer_reviews_assigned = true end - self.save + save res end @@ -2707,7 +2707,7 @@ def sorted_review_candidates(peer_review_params, current_submission, candidate_s candidates_for_review.sort_by do |c| [ # prefer those who need reviews done - assessor_id_map[c.id].count < self.peer_review_count ? CanvasSort::First : CanvasSort::Last, + assessor_id_map[c.id].count < peer_review_count ? CanvasSort::First : CanvasSort::Last, # then prefer those who are not reviewing this submission assessor_id_map[current_submission.id].include?(c.id) ? CanvasSort::Last : CanvasSort::First, # then prefer those who need the most reviews done (that way we don't run the risk of @@ -2728,16 +2728,16 @@ def current_candidate_set(peer_review_params, current_submission, existing) # don't assign to ourselves candidate_set.delete(current_submission.id) - if self.group_category_id && !self.intra_group_peer_reviews + if group_category_id && !intra_group_peer_reviews if current_submission.group_id # don't assign to our group partners (assuming we have a group) group_ids = peer_review_params[:submissions].select { |s| candidate_set.include?(s.id) && current_submission.group_id == s.group_id }.map(&:id) candidate_set -= group_ids end else - if self.discussion_topic? && self.discussion_topic.group_category_id + if discussion_topic? && discussion_topic.group_category_id # only assign to other members in the group discussion - child_topic = self.discussion_topic.child_topic_for(current_submission.user) + child_topic = discussion_topic.child_topic_for(current_submission.user) if child_topic other_member_ids = child_topic.discussion_entries.except(:order).active.distinct.pluck(:user_id) candidate_set &= peer_review_params[:submissions].select { |s| other_member_ids.include?(s.user_id) }.map(&:id) @@ -2760,21 +2760,21 @@ def next_auto_peer_review_date(current_auto_peer_review_date = nil) def auto_peer_review_dates # When a date is specified for assigning peer reviews, that is the ONLY # date that should be used. - return [self.peer_reviews_assign_at] if self.peer_reviews_assign_at.present? + return [peer_reviews_assign_at] if peer_reviews_assign_at.present? # When the `due_at` on the assignment applies to some assignees, it should # be used as one of the dates for automatic peer review assignment. dates = [] - dates.push(self.due_at) unless self.due_at.blank? || self.only_visible_to_overrides? + dates.push(due_at) unless due_at.blank? || only_visible_to_overrides? # Each unique override date is likely a time at which peer reviews will # need to be assigned. - override_dates = self.assignment_overrides - .active - .where(due_at_overridden: true) - .where.not(due_at: nil) - .distinct - .pluck(:due_at) + override_dates = assignment_overrides + .active + .where(due_at_overridden: true) + .where.not(due_at: nil) + .distinct + .pluck(:due_at) # Return all of the unique dates from above in chronological order. (dates + override_dates).sort.uniq @@ -2791,7 +2791,7 @@ def peer_reviews_assign_at=(val) end def has_peer_reviews? - self.peer_reviews + peer_reviews end scope :include_submitted_count, -> { @@ -3144,7 +3144,7 @@ def infer_comment_context_from_filename(fullpath) submission_types assignment_group_id allowed_extensions group_category_id notify_of_update peer_reviews workflow_state].freeze def frozen? - !!(self.freeze_on_copy && self.copied && + !!(freeze_on_copy && copied && PluginSetting.settings_for_plugin(:assignment_freezer)) end @@ -3154,7 +3154,7 @@ def frozen? def frozen_for_user?(user) return true if user.blank? - frozen? && !self.context.grants_right?(user, :manage_frozen_assignments) + frozen? && !context.grants_right?(user, :manage_frozen_assignments) end def frozen_attributes_for_user(user) @@ -3169,7 +3169,7 @@ def att_frozen?(att, user = nil) if (settings = PluginSetting.settings_for_plugin(:assignment_freezer)) if Canvas::Plugin.value_to_boolean(settings[att.to_s]) if user - return !self.context.grants_right?(user, :manage_frozen_assignments) + return !context.grants_right?(user, :manage_frozen_assignments) else return true end @@ -3184,14 +3184,14 @@ def can_copy?(user) end def frozen_atts_not_altered - return if self.copying + return if copying FREEZABLE_ATTRIBUTES.each do |att| - if self.changes[att] && att_frozen?(att, @updating_user) - self.errors.add(att, - t('errors.cannot_save_att', - "You don't have permission to edit the locked attribute %{att_name}", - :att_name => att)) + if changes[att] && att_frozen?(att, @updating_user) + errors.add(att, + t('errors.cannot_save_att', + "You don't have permission to edit the locked attribute %{att_name}", + :att_name => att)) end end end @@ -3221,10 +3221,10 @@ def self.suspend_grading_period_grade_recalculation(&block) def update_cached_due_dates return unless update_cached_due_dates? - self.clear_cache_key(:availability) - self.quiz.clear_cache_key(:availability) if self.quiz? + clear_cache_key(:availability) + quiz.clear_cache_key(:availability) if quiz? - unless self.saved_by == :migration + unless saved_by == :migration relevant_changes = saved_changes.slice(:due_at, :workflow_state, :only_visible_to_overrides, :anonymous_grading).inspect Rails.logger.debug "GRADES: recalculating because scope changed for Assignment #{global_id}: #{relevant_changes}" DueDateCacher.recompute(self, update_grades: true) @@ -3242,15 +3242,15 @@ def update_cached_due_dates? end def update_due_date_smart_alerts - unless self.saved_by == :migration - if self.due_at.nil? || self.due_at < Time.zone.now - ScheduledSmartAlert.find_by(context_type: self.class.name, context_id: self.id, alert_type: :due_date_reminder)&.destroy + unless saved_by == :migration + if due_at.nil? || due_at < Time.zone.now + ScheduledSmartAlert.find_by(context_type: self.class.name, context_id: id, alert_type: :due_date_reminder)&.destroy else ScheduledSmartAlert.upsert( context_type: self.class.name, - context_id: self.id, + context_id: id, alert_type: :due_date_reminder, - due_at: self.due_at, + due_at: due_at, root_account_id: root_account.id ) end @@ -3297,7 +3297,7 @@ def has_student_submissions? attr_writer :has_student_submissions def group_category_deleted_with_submissions? - self.group_category.try(:deleted_at?) && self.has_student_submissions? + group_category.try(:deleted_at?) && has_student_submissions? end def self.with_student_submission_count @@ -3347,13 +3347,13 @@ def self.assignment_ids_with_submissions(assignment_ids) # override so validations are called def publish self.workflow_state = 'published' - self.save + save end # override so validations are called def unpublish self.workflow_state = 'unpublished' - self.save + save end def unmute! @@ -3445,7 +3445,7 @@ def self.sis_grade_export_enabled?(context) def run_if_overrides_changed!(student_ids = nil, updating_user = nil) relocked_modules = [] - self.relock_modules!(relocked_modules, student_ids) + relock_modules!(relocked_modules, student_ids) each_submission_type { |submission| submission&.relock_modules!(relocked_modules, student_ids) } update_grades = if only_visible_to_overrides? @@ -3461,13 +3461,13 @@ def run_if_overrides_changed!(student_ids = nil, updating_user = nil) def run_if_overrides_changed_later!(student_ids: nil, updating_user: nil) return if self.class.suspended_callback?(:update_cached_due_dates, :save) - self.clear_cache_key(:availability) - self.quiz.clear_cache_key(:availability) if self.quiz? + clear_cache_key(:availability) + quiz.clear_cache_key(:availability) if quiz? enqueuing_args = if student_ids - { strand: "assignment_overrides_changed_for_students_#{self.global_id}" } + { strand: "assignment_overrides_changed_for_students_#{global_id}" } else - { singleton: "assignment_overrides_changed_#{self.global_id}" } + { singleton: "assignment_overrides_changed_#{global_id}" } end delay_if_production(**enqueuing_args).run_if_overrides_changed!(student_ids, updating_user) @@ -3743,7 +3743,7 @@ def hide_submissions(progress: nil, submission_ids: nil, skip_updating_timestamp def broadcast_submissions_posted(posting_params) @posting_params_for_notifications = posting_params - self.broadcast_notifications + broadcast_notifications @posting_params_for_notifications = nil end @@ -3786,11 +3786,11 @@ def self.from_secure_lti_params(secure_params) lti_context_id = Lti::Security.decoded_lti_assignment_id(secure_params) return nil if lti_context_id.blank? - self.find_by(lti_context_id: lti_context_id) + find_by(lti_context_id: lti_context_id) end def active_rubric_association? - !!self.rubric_association&.active? + !!rubric_association&.active? end def can_reassign?(grader) @@ -3896,11 +3896,11 @@ def gather_override_data(overrides) o end override_ids = overrides.pluck(:id).to_set - self.assignment_overrides.reject { |o| override_ids.include? o[:id] } + overrides + assignment_overrides.reject { |o| override_ids.include? o[:id] } + overrides end def active_assignment_overrides? - self.assignment_overrides.exists? + assignment_overrides.exists? end def assignment_name_length_ok? @@ -3909,7 +3909,7 @@ def assignment_name_length_ok? # Due to the removal of the multiple `validates_length_of :title` validations we need this nil check # here to act as those validations so we can reduce the number of validations for this attribute # to just one single check - return if self.nil? || self.title.nil? + return if nil? || self.title.nil? if self.title.to_s.length > name_length && self.grading_type != 'not_graded' errors.add(:title, I18n.t('The title cannot be longer than %{length} characters', length: name_length)) diff --git a/app/models/assignment_group.rb b/app/models/assignment_group.rb index ae9ba222a8456..22fddb450e517 100644 --- a/app/models/assignment_group.rb +++ b/app/models/assignment_group.rb @@ -66,77 +66,77 @@ class AssignmentGroup < ActiveRecord::Base after_destroy :clear_context_has_assignment_group_cache def generate_default_values - if self.name.blank? + if name.blank? self.name = t 'default_title', "Assignments" end - if !self.group_weight || self.group_weight.nan? + if !group_weight || group_weight.nan? self.group_weight = 0 end - self.default_assignment_name = self.name - self.default_assignment_name = self.default_assignment_name.singularize if I18n.locale == :en - self.position = self.position_was if self.will_save_change_to_position? && self.position.nil? # don't allow setting to nil + self.default_assignment_name = name + self.default_assignment_name = default_assignment_name.singularize if I18n.locale == :en + self.position = position_was if will_save_change_to_position? && position.nil? # don't allow setting to nil end protected :generate_default_values def update_student_grades - if self.saved_change_to_rules? || self.saved_change_to_group_weight? - unless self.saved_by == :migration - self.class.connection.after_transaction_commit { self.context.recompute_student_scores } + if saved_change_to_rules? || saved_change_to_group_weight? + unless saved_by == :migration + self.class.connection.after_transaction_commit { context.recompute_student_scores } end end end def set_context_code - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" + self.context_code = "#{context_type.underscore}_#{context_id}" end set_policy do - given { |user, session| self.context.grants_any_right?(user, session, :read, :view_all_grades, :manage_grades) } + given { |user, session| context.grants_any_right?(user, session, :read, :view_all_grades, :manage_grades) } can :read given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments) + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments) end can :read and can :create and can :update given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_add) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_add) end can :read and can :create given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_edit) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_edit) end can :read and can :update given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments) && - (self.context.account_membership_allows(user) || + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments) && + (context.account_membership_allows(user) || !any_assignment_in_closed_grading_period?) end can :delete given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_delete) && - (self.context.account_membership_allows(user) || + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_delete) && + (context.account_membership_allows(user) || !any_assignment_in_closed_grading_period?) end can :delete end def restore(try_to_selectively_undelete_assignments = true) - to_restore = self.assignments.include_submittables + to_restore = assignments.include_submittables if try_to_selectively_undelete_assignments # It's a pretty good guess that if an assignment was modified at the same # time that this group was last modified, that assignment was deleted # along with this group. This might help avoid undeleting assignments that # were deleted earlier. - to_restore = to_restore.where('updated_at >= ?', self.updated_at.utc) + to_restore = to_restore.where('updated_at >= ?', updated_at.utc) end undestroy(active_state: 'available') restore_scores @@ -180,7 +180,7 @@ def rules_hash=(incoming_hash) end def points_possible - self.assignments.reduce(0) { |sum, assignment| sum + (assignment.points_possible || 0) } + assignments.reduce(0) { |sum, assignment| sum + (assignment.points_possible || 0) } end scope :include_active_assignments, -> { preload(:active_assignments) } @@ -190,7 +190,7 @@ def points_possible scope :for_course, lambda { |course| where(:context_id => course, :context_type => 'Course') } def course_grading_change - self.context.grade_weight_changed! if saved_change_to_group_weight? && self.context && self.context.group_weighting_scheme == 'percent' + context.grade_weight_changed! if saved_change_to_group_weight? && context && context.group_weighting_scheme == 'percent' true end @@ -229,18 +229,18 @@ def self.add_never_drop_assignment(group, assignment) def has_frozen_assignments?(user) return false unless PluginSetting.settings_for_plugin(:assignment_freezer) - return false if self.active_assignments.empty? + return false if active_assignments.empty? - self.active_assignments.any? do |assignment| + active_assignments.any? do |assignment| assignment.frozen_for_user?(user) end end def has_frozen_assignment_group_id_assignment?(user) return false unless PluginSetting.settings_for_plugin(:assignment_freezer) - return false if self.active_assignments.empty? + return false if active_assignments.empty? - self.active_assignments.any? do |assignment| + active_assignments.any? do |assignment| assignment.att_frozen?(:assignment_group_id, user) end end @@ -252,7 +252,7 @@ def any_assignment_in_closed_grading_period? def visible_assignments(user, includes: [], assignment_ids: []) self.class.visible_assignments( user, - self.context, + context, [self], includes: includes, assignment_ids: assignment_ids @@ -279,12 +279,12 @@ def self.visible_assignments(user, context, assignment_groups, includes: [], ass def move_assignments_to(move_to_id) new_group = context.assignment_groups.active.find(move_to_id) order = new_group.assignments.active.pluck(:id) - ids_to_change = self.assignments.active.pluck(:id) + ids_to_change = assignments.active.pluck(:id) order += ids_to_change Assignment.where(:id => ids_to_change).update_all(:assignment_group_id => new_group.id, :updated_at => Time.now.utc) unless ids_to_change.empty? Assignment.where(id: order).first.update_order(order) unless order.empty? new_group.touch - self.reload + reload end private diff --git a/app/models/assignment_override.rb b/app/models/assignment_override.rb index d2726967a929b..e7ffd480c7b4b 100644 --- a/app/models/assignment_override.rb +++ b/app/models/assignment_override.rb @@ -90,7 +90,7 @@ class AssignmentOverride < ActiveRecord::Base def set_not_empty? overridable = assignment? ? assignment : quiz - ['CourseSection', 'Group', SET_TYPE_NOOP].include?(self.set_type) || + ['CourseSection', 'Group', SET_TYPE_NOOP].include?(set_type) || (set.any? && overridable.context.current_enrollments.where(user_id: set).exists?) end @@ -142,23 +142,23 @@ def update_cached_due_dates? def update_cached_due_dates if update_cached_due_dates? - if self.assignment + if assignment assignment.clear_cache_key(:availability) DueDateCacher.recompute(assignment) end - self.quiz&.clear_cache_key(:availability) + quiz&.clear_cache_key(:availability) end end def update_due_date_smart_alerts - if self.due_at.nil? || self.due_at < Time.zone.now - ScheduledSmartAlert.find_by(context_type: self.class.name, context_id: self.id, alert_type: :due_date_reminder)&.destroy + if due_at.nil? || due_at < Time.zone.now + ScheduledSmartAlert.find_by(context_type: self.class.name, context_id: id, alert_type: :due_date_reminder)&.destroy else ScheduledSmartAlert.upsert( context_type: self.class.name, - context_id: self.id, + context_id: id, alert_type: :due_date_reminder, - due_at: self.due_at, + due_at: due_at, root_account_id: root_account_id ) end @@ -187,13 +187,13 @@ def quiz? alias_method :destroy_permanently!, :destroy def destroy transaction do - self.assignment_override_students.reload.destroy_all + assignment_override_students.reload.destroy_all self.workflow_state = 'deleted' - self.default_values - self.save!(validate: false) + default_values + save!(validate: false) end - ScheduledSmartAlert.where(context_type: self.class.name, context_id: self.id).destroy_all + ScheduledSmartAlert.where(context_type: self.class.name, context_id: id).destroy_all end scope :active, -> { where(:workflow_state => 'active') } @@ -369,9 +369,9 @@ def applies_to_admins end def notify_change? - self.assignment&.context&.available? && - self.assignment.published? && - self.assignment.created_at < 3.hours.ago && + assignment&.context&.available? && + assignment.published? && + assignment.created_at < 3.hours.ago && (saved_change_to_workflow_state? || saved_change_to_due_at_overridden? || (due_at_overridden && !Assignment.due_dates_equal?(due_at, due_at_before_last_save))) @@ -400,8 +400,8 @@ def self.title_from_student_count(student_count) def destroy_if_empty_set return unless set_type == 'ADHOC' - self.assignment_override_students.reload if self.id_before_last_save.nil? # fixes a problem with rails 4.2 caching an empty association scope - self.destroy if set.empty? + assignment_override_students.reload if id_before_last_save.nil? # fixes a problem with rails 4.2 caching an empty association scope + destroy if set.empty? end has_a_broadcast_policy @@ -432,6 +432,6 @@ def root_account_id end def set_root_account_id - self.write_attribute(:root_account_id, root_account_id) unless read_attribute(:root_account_id) + write_attribute(:root_account_id, root_account_id) unless read_attribute(:root_account_id) end end diff --git a/app/models/assignment_override_student.rb b/app/models/assignment_override_student.rb index f384c94d0ed0c..9c921ee54070c 100644 --- a/app/models/assignment_override_student.rb +++ b/app/models/assignment_override_student.rb @@ -129,7 +129,7 @@ def update_cached_due_dates assignment.clear_cache_key(:availability) DueDateCacher.recompute_users_for_course(user_id, assignment.context, [assignment]) end - self.quiz&.clear_cache_key(:availability) + quiz&.clear_cache_key(:availability) end def set_root_account_id diff --git a/app/models/assignment_student_visibility.rb b/app/models/assignment_student_visibility.rb index c8fb117e8123c..c727e5f4958a4 100644 --- a/app/models/assignment_student_visibility.rb +++ b/app/models/assignment_student_visibility.rb @@ -68,7 +68,7 @@ def self.visible_assignment_ids_for_user(user_id, course_ids = nil) if course_ids opts[:course_id] = course_ids end - self.where(opts).pluck(:assignment_id) + where(opts).pluck(:assignment_id) end # readonly? is not checked in destroy though diff --git a/app/models/attachment.rb b/app/models/attachment.rb index b7aff97ac84b7..68e9f4fe68fd9 100644 --- a/app/models/attachment.rb +++ b/app/models/attachment.rb @@ -141,7 +141,7 @@ def store # Haaay... you're changing stuff here? Don't forget about the Thumbnail model # too, it cares about local vs s3 storage. has_attachment( - :storage => self.store_type.key, + :storage => store_type.key, :path_prefix => file_store_config['path_prefix'], :s3_access => 'private', :thumbnails => { :thumb => '128x128' }, @@ -187,7 +187,7 @@ def find_attachment_possibly_replaced(att) # attachment in the same context and the same full path, we return that # instead, to emulate replacing a file without having to update every # by-id reference in every user content field. - if self.respond_to?(:proxy_association) + if respond_to?(:proxy_association) owner = proxy_association.owner end @@ -214,7 +214,7 @@ def touch_context_if_appropriate end def run_before_attachment_saved - @after_attachment_saved_workflow_state = self.workflow_state + @after_attachment_saved_workflow_state = workflow_state self.workflow_state = 'unattached' end @@ -222,7 +222,7 @@ def run_before_attachment_saved # note, that the time it takes to send to s3 is the bad guy. # It blocks and makes the user wait. def run_after_attachment_saved - old_workflow_state = self.workflow_state + old_workflow_state = workflow_state if workflow_state == 'unattached' && @after_attachment_saved_workflow_state self.workflow_state = @after_attachment_saved_workflow_state @after_attachment_saved_workflow_state = nil @@ -234,14 +234,14 @@ def run_after_attachment_saved end # directly update workflow_state so we don't trigger another save cycle - if old_workflow_state != self.workflow_state - self.shard.activate do - self.class.where(:id => self).update_all(:workflow_state => self.workflow_state) + if old_workflow_state != workflow_state + shard.activate do + self.class.where(:id => self).update_all(:workflow_state => workflow_state) end end # try an infer encoding if it would be useful to do so - delay.infer_encoding if self.encoding.nil? && self.content_type&.include?('text') && self.context_type != 'SisBatch' + delay.infer_encoding if encoding.nil? && content_type&.include?('text') && context_type != 'SisBatch' if respond_to?(:process_attachment, true) automatic_thumbnail_sizes.each do |suffix| delay_if_production(singleton: "attachment_thumbnail_#{global_id}_#{suffix}") @@ -284,7 +284,7 @@ def self.valid_utf8?(file) end def infer_encoding - return unless self.encoding.nil? + return unless encoding.nil? begin if self.class.valid_utf8?(self.open) @@ -295,7 +295,7 @@ def infer_encoding Attachment.where(:id => self).update_all(:encoding => '') end rescue IOError => e - logger.error("Error inferring encoding for attachment #{self.global_id}: #{e.message}") + logger.error("Error inferring encoding for attachment #{global_id}: #{e.message}") end end @@ -307,15 +307,15 @@ def parent_id; end attr_accessor :clone_updated def clone_for(context, dup = nil, options = {}) - if !self.cloned_item && !self.new_record? + if !cloned_item && !new_record? self.cloned_item = ClonedItem.create(:original_item => self) # do we even use this for anything? - self.shard.activate do - Attachment.where(:id => self).update_all(:cloned_item_id => self.cloned_item.id) # don't touch it for no reason + shard.activate do + Attachment.where(:id => self).update_all(:cloned_item_id => cloned_item.id) # don't touch it for no reason end end existing = context.attachments.active.find_by(id: self) - options[:cloned_item_id] ||= self.cloned_item_id + options[:cloned_item_id] ||= cloned_item_id options[:migration_id] ||= CC::CCHelper.create_key(self) existing ||= Attachment.find_existing_attachment_for_clone(context, options.merge(:active_only => true)) return existing if existing && !options[:overwrite] && !options[:force_copy] @@ -327,32 +327,32 @@ def clone_for(context, dup = nil, options = {}) excluded_atts = EXCLUDED_COPY_ATTRIBUTES excluded_atts += ["locked", "hidden"] if dup == existing && !options[:migration]&.for_master_course_import? - dup.assign_attributes(self.attributes.except(*excluded_atts)) + dup.assign_attributes(attributes.except(*excluded_atts)) dup.context = context - if self.usage_rights && self.shard != context.shard - attrs = self.usage_rights.attributes.slice('use_justification', 'license', 'legal_copyright') + if usage_rights && shard != context.shard + attrs = usage_rights.attributes.slice('use_justification', 'license', 'legal_copyright') new_rights = context.usage_rights.detect { |ur| attrs.all? { |k, v| ur.attributes[k] == v } } new_rights ||= context.usage_rights.create(attrs) dup.usage_rights = new_rights end # avoid cycles (a -> b -> a) and self-references (a -> a) in root_attachment_id pointers - if dup.new_record? || ![self.id, self.root_attachment_id].include?(dup.id) - if self.shard == dup.shard - dup.root_attachment_id = self.root_attachment_id || self.id + if dup.new_record? || ![id, root_attachment_id].include?(dup.id) + if shard == dup.shard + dup.root_attachment_id = root_attachment_id || id else if (existing_attachment = dup.find_existing_attachment_for_md5) dup.root_attachment = existing_attachment else - dup.write_attribute(:filename, self.filename) + dup.write_attribute(:filename, filename) Attachments::Storage.store_for_attachment(dup, self.open) end end end - dup.write_attribute(:filename, self.filename) unless dup.read_attribute(:filename) || dup.root_attachment_id? + dup.write_attribute(:filename, filename) unless dup.read_attribute(:filename) || dup.root_attachment_id? dup.migration_id = options[:migration_id] dup.mark_as_importing!(options[:migration]) if options[:migration] dup.shard.activate do - if Attachment.s3_storage? && !instfs_hosted? && context.try(:root_account) && self.namespace != context.root_account.file_namespace + if Attachment.s3_storage? && !instfs_hosted? && context.try(:root_account) && namespace != context.root_account.file_namespace dup.save_without_broadcasting! dup.make_rootless dup.change_namespace(context.root_account.file_namespace) @@ -360,7 +360,7 @@ def clone_for(context, dup = nil, options = {}) end dup.updated_at = Time.zone.now dup.clone_updated = true - dup.set_publish_state_for_usage_rights unless self.locked? + dup.set_publish_state_for_usage_rights unless locked? dup end @@ -375,7 +375,7 @@ def self.find_existing_attachment_for_clone(context, options = {}) end def copy_to_folder!(folder, on_duplicate = :rename) - copy = self.clone_for(folder.context, nil, force_copy: true) + copy = clone_for(folder.context, nil, force_copy: true) copy.folder = folder copy.save! copy.handle_duplicates(on_duplicate) @@ -385,9 +385,9 @@ def copy_to_folder!(folder, on_duplicate = :rename) def ensure_media_object return true if self.class.skip_media_object_creation? - in_the_right_state = self.file_state == 'available' && self.workflow_state !~ /^unattached/ - if in_the_right_state && self.media_entry_id == 'maybe' && - self.content_type && self.content_type.match(/\A(video|audio)/) + in_the_right_state = file_state == 'available' && workflow_state !~ /^unattached/ + if in_the_right_state && media_entry_id == 'maybe' && + content_type && content_type.match(/\A(video|audio)/) build_media_object end end @@ -407,8 +407,8 @@ def build_media_object end def assert_attachment - if !self.to_be_zipped? && !self.zipping? && !self.errored? && !self.deleted? && (!filename || !content_type || !downloadable?) - self.errors.add(:base, t('errors.not_found', "File data could not be found")) + if !to_be_zipped? && !zipping? && !errored? && !deleted? && (!filename || !content_type || !downloadable?) + errors.add(:base, t('errors.not_found', "File data could not be found")) throw :abort end end @@ -463,29 +463,29 @@ def flag_as_recently_created end protected :flag_as_recently_created def recently_created? - @recently_created || (self.created_at && self.created_at > Time.now - (60 * 5)) + @recently_created || (created_at && created_at > Time.now - (60 * 5)) end def after_extension - res = self.extension[1..] rescue nil + res = extension[1..] rescue nil res = nil if res == "" || res == "unknown" res end def assert_file_extension self.content_type = nil if content_type == 'application/x-unknown' || content_type&.include?('ERROR') - self.content_type ||= self.mimetype(self.filename) - if self.filename && self.filename.split(".").length < 2 + self.content_type ||= mimetype(filename) + if filename && filename.split(".").length < 2 # we actually have better luck assuming zip files without extensions # are docx files than assuming they're zip files self.content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' if content_type&.include?('zip') - ext = self.extension - self.write_attribute(:filename, self.filename + ext) unless ext == '.unknown' + ext = extension + write_attribute(:filename, filename + ext) unless ext == '.unknown' end end def extension - res = (self.filename || "").match(/(\.[^.]*)\z/).to_s + res = (filename || "").match(/(\.[^.]*)\z/).to_s res = nil if res == "" if !res || res == "" res = File.mime_types[self.content_type].to_s rescue nil @@ -497,29 +497,29 @@ def extension end def default_values - self.modified_at = Time.now.utc if self.modified_at.nil? - self.display_name = nil if self.display_name && self.display_name.empty? + self.modified_at = Time.now.utc if modified_at.nil? + self.display_name = nil if display_name && display_name.empty? self.display_name ||= unencoded_filename self.file_state ||= "available" - self.assert_file_extension - self.folder_id = nil if !self.folder || self.folder.context != self.context - self.folder_id = nil if self.folder&.deleted? && !self.deleted? - self.folder_id ||= Folder.unfiled_folder(self.context).id rescue nil + assert_file_extension + self.folder_id = nil if !folder || folder.context != context + self.folder_id = nil if folder&.deleted? && !deleted? + self.folder_id ||= Folder.unfiled_folder(context).id rescue nil self.folder_id ||= Folder.root_folders(context).first.id rescue nil - if self.root_attachment && self.new_record? + if root_attachment && new_record? [:md5, :size, :content_type].each do |key| - self.send("#{key}=", self.root_attachment.send(key)) + send("#{key}=", root_attachment.send(key)) end self.workflow_state = 'processed' - self.write_attribute(:filename, self.root_attachment.filename) + write_attribute(:filename, root_attachment.filename) end - self.context = self.folder.context if self.folder && (!self.context || (self.context.respond_to?(:is_a_context?) && self.context.is_a_context?)) + self.context = folder.context if folder && (!context || (context.respond_to?(:is_a_context?) && context.is_a_context?)) - if self.respond_to?(:namespace=) && self.new_record? + if respond_to?(:namespace=) && new_record? self.namespace = infer_namespace end - self.media_entry_id ||= 'maybe' if self.new_record? && self.previewable_media? + self.media_entry_id ||= 'maybe' if new_record? && previewable_media? end protected :default_values @@ -560,8 +560,8 @@ def infer_namespace # isn't any code still accessing the namespace for the account id directly. d ns = root_attachment.try(:namespace) if root_attachment_id ns ||= Attachment.current_namespace - ns ||= self.context.root_account.file_namespace rescue nil - ns ||= self.context.account.file_namespace rescue nil + ns ||= context.root_account.file_namespace rescue nil + ns ||= context.account.file_namespace rescue nil if Rails.env.development? && Attachment.local_storage? ns ||= "" ns = "_localstorage_/#{ns}" unless ns.start_with?('_localstorage_/') @@ -572,13 +572,13 @@ def infer_namespace end def change_namespace(new_namespace) - raise "change_namespace must be called on a root attachment" if self.root_attachment - return if new_namespace == self.namespace + raise "change_namespace must be called on a root attachment" if root_attachment + return if new_namespace == namespace - old_full_filename = self.full_filename + old_full_filename = full_filename write_attribute(:namespace, new_namespace) - self.store.change_namespace(old_full_filename) + store.change_namespace(old_full_filename) shard.activate do Attachment.where("id=? OR root_attachment_id=?", self, self).update_all(namespace: new_namespace) end @@ -593,7 +593,7 @@ def process_s3_details!(details) self.content_type = details[:content_type] self.size = details[:content_length] - self.shard.activate do + shard.activate do if (existing_attachment = find_existing_attachment_for_md5) if existing_attachment.s3object.exists? # deduplicate. the existing attachment's s3object should be the same as @@ -643,8 +643,8 @@ def ajax_upload_params(local_upload_url, s3_success_url, options = {}) # there is no way to add custom parameters to the condition, like we do # with `extras` below. options[:datetime] = Time.now.utc.strftime("%Y%m%dT%H%M%SZ") - res = self.store.initialize_ajax_upload_params(local_upload_url, s3_success_url, options) - policy = self.store.amend_policy_conditions(policy, datetime: options[:datetime]) + res = store.initialize_ajax_upload_params(local_upload_url, s3_success_url, options) + policy = store.amend_policy_conditions(policy, datetime: options[:datetime]) if res[:upload_params]['folder'].present? policy['conditions'] << ['starts-with', '$folder', ''] @@ -665,7 +665,7 @@ def ajax_upload_params(local_upload_url, s3_success_url, options = {}) policy['conditions'] += extras policy_encoded = Base64.encode64(policy.to_json).delete("\n") - sig_key, sig_val = self.store.sign_policy(policy_encoded, options[:datetime]) + sig_key, sig_val = store.sign_policy(policy_encoded, options[:datetime]) res[:id] = id res[:upload_params].merge!({ @@ -683,7 +683,7 @@ def self.decode_policy(policy_str, signature_str) return nil if policy_str.blank? || signature_str.blank? signature = Base64.decode64(signature_str) - return nil if OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha1"), self.shared_secret, policy_str) != signature + return nil if OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha1"), shared_secret, policy_str) != signature policy = JSON.parse(Base64.decode64(policy_str)) return nil unless Time.zone.parse(policy['expiration']) >= Time.now @@ -695,7 +695,7 @@ def self.decode_policy(policy_str, signature_str) end def unencoded_filename - CGI.unescape(self.filename || t(:default_filename, "File")) + CGI.unescape(filename || t(:default_filename, "File")) end def quota_exemption_key @@ -732,7 +732,7 @@ def self.get_quota(context) attachment_scope = attachment_scope.where.not(id: excluded_attachment_ids) if excluded_attachment_ids.any? end - min = self.minimum_size_for_quota + min = minimum_size_for_quota # translated to ruby this is [size, min].max || 0 quota_used = attachment_scope.sum("COALESCE(CASE when size < #{min} THEN #{min} ELSE size END, 0)").to_i end @@ -746,39 +746,39 @@ def self.get_quota(context) # (for example, to check if a new attachment of size additional_quota would # put the context over quota.) def self.over_quota?(context, additional_quota = nil) - quota = self.get_quota(context) + quota = get_quota(context) quota[:quota] < quota[:quota_used] + (additional_quota || 0) end def self.quota_available(context) - quota = self.get_quota(context) + quota = get_quota(context) [0, quota[:quota] - quota[:quota_used]].max end def handle_duplicates(method, opts = {}) - return [] unless method.present? && self.folder + return [] unless method.present? && folder - method = if self.folder.for_submissions? + method = if folder.for_submissions? :rename else method.to_sym end if method == :overwrite - atts = self.shard.activate { self.folder.active_file_attachments.where("display_name=? AND id<>?", self.display_name, self.id).to_a } + atts = shard.activate { folder.active_file_attachments.where("display_name=? AND id<>?", self.display_name, id).to_a } method = :rename if atts.any? { |att| att.editing_restricted?(:any) } end deleted_attachments = [] if method == :rename begin - self.save! unless self.id + save! unless id valid_name = false - self.shard.activate do + shard.activate do iter_count = 1 until valid_name - existing_names = self.folder.active_file_attachments.where.not(id: self.id).pluck(:display_name) + existing_names = folder.active_file_attachments.where.not(id: id).pluck(:display_name) new_name = opts[:name] || self.display_name self.display_name = Attachment.make_unique_filename(new_name, existing_names, iter_count) @@ -801,15 +801,15 @@ def handle_duplicates(method, opts = {}) end elsif method == :overwrite && atts.any? shard.activate do - Attachment.where(:id => atts).update_all(replacement_attachment_id: self.id) # so we can find the new file in content links + Attachment.where(:id => atts).update_all(replacement_attachment_id: id) # so we can find the new file in content links copy_access_attributes!(atts) atts.each do |a| # update content tags to refer to the new file - if ContentTag.where(:content_id => a, :content_type => 'Attachment').update_all(content_id: self.id, updated_at: Time.now.utc) > 0 - ContextModule.where(:id => ContentTag.where(:content_id => self.id, :content_type => 'Attachment').select(:context_module_id)).touch_all + if ContentTag.where(:content_id => a, :content_type => 'Attachment').update_all(content_id: id, updated_at: Time.now.utc) > 0 + ContextModule.where(:id => ContentTag.where(:content_id => id, :content_type => 'Attachment').select(:context_module_id)).touch_all end # update replacement pointers pointing at the overwritten file - context.attachments.where(:replacement_attachment_id => a).update_all(replacement_attachment_id: self.id) + context.attachments.where(:replacement_attachment_id => a).update_all(replacement_attachment_id: id) # delete the overwritten file (unless the caller is queueing them up) a.destroy unless opts[:caller_will_destroy] deleted_attachments << a @@ -842,11 +842,11 @@ def assign_uuid def reset_uuid! self.uuid = CanvasSlug.generate_securish_uuid - self.save! + save! end def inline_content? - self.content_type.start_with?('text') || self.extension == '.html' || self.extension == '.htm' || self.extension == '.swf' + self.content_type.start_with?('text') || extension == '.html' || extension == '.htm' || extension == '.swf' end def self.shared_secret @@ -872,7 +872,7 @@ def public_url(**options) should_download = options.delete(:download) disposition = should_download ? "attachment" : "inline" options[:response_content_disposition] = "#{disposition}; #{disposition_filename}" - self.authenticated_s3_url(**options) + authenticated_s3_url(**options) end end @@ -996,11 +996,11 @@ def thumbnail_url(options = {}) return nil if Attachment.skip_thumbnails geometry = options[:size] - if self.thumbnail || geometry.present? - to_use = thumbnail_for_size(geometry) || self.thumbnail + if thumbnail || geometry.present? + to_use = thumbnail_for_size(geometry) || thumbnail to_use.cached_s3_url - elsif self.media_object&.media_id - CanvasKaltura::ClientV3.new.thumbnail_url(self.media_object.media_id, + elsif media_object&.media_id + CanvasKaltura::ClientV3.new.thumbnail_url(media_object.media_id, :width => options[:width] || 140, :height => options[:height] || 100, :vid_sec => options[:video_seconds] || 5) @@ -1017,7 +1017,7 @@ def thumbnail_for_size(geometry) end def self.allows_thumbnails_of_size?(geometry) - self.dynamic_thumbnail_sizes.include?(geometry) + dynamic_thumbnail_sizes.include?(geometry) end def self.truncate_filename(filename, max_len, &block) @@ -1132,12 +1132,12 @@ def disposition_filename protected :disposition_filename def attachment_path_id - a = (self.respond_to?(:root_attachment) && self.root_attachment) || self + a = (respond_to?(:root_attachment) && root_attachment) || self ((a.respond_to?(:parent_id) && a.parent_id) || a.id).to_s end def filename - read_attribute(:filename) || self.root_attachment&.filename + read_attribute(:filename) || root_attachment&.filename end def filename=(name) @@ -1152,19 +1152,19 @@ def thumbnail end def content_directory - self.directory_name || Folder.root_folders(self.context).first.name + directory_name || Folder.root_folders(context).first.name end def to_atom(opts = {}) Atom::Entry.new do |entry| - entry.title = t(:feed_title, "File: %{title}", :title => self.context.name) unless opts[:include_context] - entry.title = t(:feed_title_with_context, "File, %{course_or_group}: %{title}", :course_or_group => self.context.name, :title => self.context.name) if opts[:include_context] - entry.authors << Atom::Person.new(:name => self.context.name) - entry.updated = self.updated_at - entry.published = self.created_at - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime("%Y-%m-%d")}:/files/#{self.feed_code}" + entry.title = t(:feed_title, "File: %{title}", :title => context.name) unless opts[:include_context] + entry.title = t(:feed_title_with_context, "File, %{course_or_group}: %{title}", :course_or_group => context.name, :title => context.name) if opts[:include_context] + entry.authors << Atom::Person.new(:name => context.name) + entry.updated = updated_at + entry.published = created_at + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime("%Y-%m-%d")}:/files/#{feed_code}" entry.links << Atom::Link.new(:rel => 'alternate', - :href => "http://#{HostUrl.context_host(self.context)}/#{context_url_prefix}/files/#{self.id}") + :href => "http://#{HostUrl.context_host(context)}/#{context_url_prefix}/files/#{id}") entry.content = Atom::Content::Html.new(self.display_name.to_s) end end @@ -1178,7 +1178,7 @@ def title end def associate_with(context) - self.attachment_associations.create(:context => context) + attachment_associations.create(:context => context) end def mime_class @@ -1246,52 +1246,52 @@ def mime_class end def associated_with_submission? - @associated_with_submission ||= self.attachment_associations.where(context_type: 'Submission').exists? + @associated_with_submission ||= attachment_associations.where(context_type: 'Submission').exists? end def user_can_read_through_context?(user, session) - self.context&.grants_right?(user, session, :read) || - (self.context.is_a?(AssessmentQuestion) && self.context.user_can_see_through_quiz_question?(user, session)) + context&.grants_right?(user, session, :read) || + (context.is_a?(AssessmentQuestion) && context.user_can_see_through_quiz_question?(user, session)) end set_policy do given do |user, session| - self.context&.grants_right?(user, session, :manage_files_edit) && - !self.associated_with_submission? && - (!self.folder || self.folder.grants_right?(user, session, :manage_contents)) + context&.grants_right?(user, session, :manage_files_edit) && + !associated_with_submission? && + (!folder || folder.grants_right?(user, session, :manage_contents)) end can :read and can :update given do |user, session| - self.context&.grants_right?(user, session, :manage_files_delete) && - !self.associated_with_submission? && - (!self.folder || self.folder.grants_right?(user, session, :manage_contents)) + context&.grants_right?(user, session, :manage_files_delete) && + !associated_with_submission? && + (!folder || folder.grants_right?(user, session, :manage_contents)) end can :read and can :delete given do |user, session| - self.context&.grants_right?(user, session, :manage_files_add) + context&.grants_right?(user, session, :manage_files_add) end can :read and can :create and can :download and can :read_as_admin - given { self.public? } + given { public? } can :read and can :download - given { |user, session| self.context&.grants_right?(user, session, :read) } # students.include? user } + given { |user, session| context&.grants_right?(user, session, :read) } # students.include? user } can :read - given { |user, session| self.context&.grants_right?(user, session, :read_as_admin) } + given { |user, session| context&.grants_right?(user, session, :read_as_admin) } can :read_as_admin given { |user, session| - user_can_read_through_context?(user, session) && !self.locked_for?(user, :check_policies => true) + user_can_read_through_context?(user, session) && !locked_for?(user, :check_policies => true) } can :read and can :download given { |_user, session| (u = session.try(:file_access_user)) && (user_can_read_through_context?(u, session) || - (self.context.respond_to?(:is_public_to_auth_users?) && self.context.is_public_to_auth_users?)) && + (context.respond_to?(:is_public_to_auth_users?) && context.is_public_to_auth_users?)) && session['file_access_expiration'] && session['file_access_expiration'].to_i > Time.zone.now.to_i } can :read @@ -1299,8 +1299,8 @@ def user_can_read_through_context?(user, session) given { |_user, session| (u = session.try(:file_access_user)) && (user_can_read_through_context?(u, session) || - (self.context.respond_to?(:is_public_to_auth_users?) && self.context.is_public_to_auth_users?)) && - !self.locked_for?(u, :check_policies => true) && + (context.respond_to?(:is_public_to_auth_users?) && context.is_public_to_auth_users?)) && + !locked_for?(u, :check_policies => true) && session['file_access_expiration'] && session['file_access_expiration'].to_i > Time.zone.now.to_i } can :download @@ -1324,8 +1324,8 @@ def next_lock_change end def locked_for?(user, opts = {}) - return false if opts[:check_policies] && self.grants_right?(user, :read_as_admin) - return { :asset_string => self.asset_string, :manually_locked => true } if self.locked || Folder.is_locked?(self.folder_id) + return false if opts[:check_policies] && grants_right?(user, :read_as_admin) + return { :asset_string => asset_string, :manually_locked => true } if locked || Folder.is_locked?(self.folder_id) RequestCache.cache(locked_request_cache_key(user)) do locked = false @@ -1334,12 +1334,12 @@ def locked_for?(user, opts = {}) if next_clear_cache.present? && next_clear_cache < (Time.zone.now + AdheresToPolicy::Cache::CACHE_EXPIRES_IN) clear_permissions(next_clear_cache) end - if self.unlock_at && Time.zone.now < self.unlock_at - locked = { :asset_string => self.asset_string, :unlock_at => self.unlock_at } - elsif self.lock_at && Time.now > self.lock_at - locked = { :asset_string => self.asset_string, :lock_at => self.lock_at } - elsif self.could_be_locked && (item = locked_by_module_item?(user, opts)) - locked = { :asset_string => self.asset_string, :context_module => item.context_module.attributes } + if unlock_at && Time.zone.now < unlock_at + locked = { :asset_string => asset_string, :unlock_at => unlock_at } + elsif lock_at && Time.now > lock_at + locked = { :asset_string => asset_string, :lock_at => lock_at } + elsif could_be_locked && (item = locked_by_module_item?(user, opts)) + locked = { :asset_string => asset_string, :context_module => item.context_module.attributes } locked[:unlock_at] = locked[:context_module]["unlock_at"] if locked[:context_module]["unlock_at"] && locked[:context_module]["unlock_at"] > Time.now.utc end locked @@ -1349,7 +1349,7 @@ def locked_for?(user, opts = {}) def hidden? return @hidden if defined?(@hidden) - @hidden = self.file_state == 'hidden' || self.folder&.hidden? + @hidden = self.file_state == 'hidden' || folder&.hidden? end def published? @@ -1370,7 +1370,7 @@ def public? end def currently_locked - self.locked || (self.lock_at && Time.zone.now > self.lock_at) || (self.unlock_at && Time.zone.now < self.unlock_at) || self.file_state == 'hidden' + locked || (lock_at && Time.zone.now > lock_at) || (unlock_at && Time.zone.now < unlock_at) || self.file_state == 'hidden' end alias_method :currently_locked?, :currently_locked @@ -1383,7 +1383,7 @@ def hidden=(val) end def context_module_action(user, action) - self.context_module_tags.each { |tag| tag.context_module_action(user, action) } + context_module_tags.each { |tag| tag.context_module_action(user, action) } end include Workflow @@ -1469,24 +1469,24 @@ def self.create_data_attachment(context, data, display_name = nil) # file_state is like workflow_state, which was already taken # possible values are: available, deleted def destroy - return if self.new_record? + return if new_record? self.file_state = 'deleted' # destroy self.deleted_at = Time.now.utc ContentTag.delete_for(self) - MediaObject.where(:attachment_id => self.id).update_all(:attachment_id => nil, :updated_at => Time.now.utc) + MediaObject.where(:attachment_id => id).update_all(:attachment_id => nil, :updated_at => Time.now.utc) save! # if the attachment being deleted belongs to a user and the uuid (hash of file) matches the avatar_image_url # then clear the avatar_image_url value. - self.context.clear_avatar_image_url_with_uuid(self.uuid) if self.context_type == 'User' && self.uuid.present? + context.clear_avatar_image_url_with_uuid(self.uuid) if context_type == 'User' && self.uuid.present? true end # this will delete the content of the attachment but not delete the attachment # object. It will replace the attachment content with a file_removed file. def destroy_content_and_replace(deleted_by_user = nil) - self.shard.activate do - att = self.root_attachment_id? ? self.root_attachment : self + shard.activate do + att = root_attachment_id? ? root_attachment : self return true if Purgatory.where(attachment_id: att).active.exists? att.send_to_purgatory(deleted_by_user) @@ -1522,7 +1522,7 @@ def self.file_removed_path def self.file_removed_base_instfs_uuid # i imagine that inevitably someone is going to change the file without knowing about any of this # so make the cache depend on the file contents - path = self.file_removed_path + path = file_removed_path @@file_removed_md5 ||= Digest::MD5.hexdigest(File.read(path)) key = "file_removed_instfs_uuid_#{@@file_removed_md5}_#{Digest::MD5.hexdigest(InstFS.app_host)}" @@ -1541,11 +1541,11 @@ def self.file_removed_base_instfs_uuid def send_to_purgatory(deleted_by_user = nil) make_rootless new_instfs_uuid = nil - if Attachment.s3_storage? && self.s3object.exists? + if Attachment.s3_storage? && s3object.exists? s3object.copy_to(bucket.object(purgatory_filename)) - elsif self.instfs_hosted? && InstFS.enabled? + elsif instfs_hosted? && InstFS.enabled? # copy to a new instfs file - new_instfs_uuid = InstFS.duplicate_file(self.instfs_uuid) + new_instfs_uuid = InstFS.duplicate_file(instfs_uuid) elsif Attachment.local_storage? FileUtils.mkdir(local_purgatory_directory) unless File.exist?(local_purgatory_directory) FileUtils.cp full_filename, local_purgatory_file @@ -1595,7 +1595,7 @@ def resurrect_from_purgatory raise "purgatory record was created before being fixed for inst-fs" end elsif Attachment.s3_storage? - old_s3object = self.bucket.object(purgatory_filename) + old_s3object = bucket.object(purgatory_filename) raise Attachment::FileDoesNotExist unless old_s3object.exists? old_s3object.copy_to(bucket.object(full_filename)) @@ -1614,14 +1614,14 @@ def dmca_file_removal end def destroy_content - raise 'must be a root_attachment' if self.root_attachment_id - return unless self.filename + raise 'must be a root_attachment' if root_attachment_id + return unless filename if instfs_hosted? - InstFS.delete_file(self.instfs_uuid) + InstFS.delete_file(instfs_uuid) self.instfs_uuid = nil elsif Attachment.s3_storage? - self.s3object.delete unless ApplicationController.test_cluster? + s3object.delete unless ApplicationController.test_cluster? else FileUtils.rm full_filename end @@ -1663,7 +1663,7 @@ def copy_attachment_content(destination) return if destination.store.exists? && open == destination.open old_content_type = self.content_type - scope = Attachment.where(:md5 => self.md5, :namespace => self.namespace, :root_attachment_id => nil) + scope = Attachment.where(:md5 => md5, :namespace => namespace, :root_attachment_id => nil) scope.update_all(:content_type => "invalid/invalid") # prevents find_existing_attachment_for_md5 from reattaching the child to the old root # TODO when RECNVS-323 is complete, branch here to call an inst-fs @@ -1678,18 +1678,18 @@ def copy_attachment_content(destination) def make_rootless return unless root_attachment_id - root = self.root_attachment + root = root_attachment return unless root self.root_attachment_id = nil root.copy_attachment_content(self) - self.run_after_attachment_saved + run_after_attachment_saved end def restore self.file_state = 'available' - if self.save - self.handle_duplicates(:rename) + if save + handle_duplicates(:rename) end true end @@ -1708,7 +1708,7 @@ def crocodocable? end def canvadocable? - for_assignment_or_submissions = self.folder&.for_submissions? || self.folder&.for_student_annotation_documents? + for_assignment_or_submissions = folder&.for_submissions? || folder&.for_student_annotation_documents? canvadocable_mime_types = for_assignment_or_submissions ? Canvadoc.submission_mime_types : Canvadoc.mime_types Canvadocs.enabled? && canvadocable_mime_types.include?(content_type_with_text_match) end @@ -1802,7 +1802,7 @@ def self.mimetype(filename) def mimetype(_filename = nil) res = Attachment.mimetype(filename) # use the object's filename, not the passed in filename - res = File.mime_type?(self.uploaded_data) if (!res || res == 'unknown/unknown') && self.uploaded_data + res = File.mime_type?(uploaded_data) if (!res || res == 'unknown/unknown') && uploaded_data res ||= "unknown/unknown" res end @@ -1811,7 +1811,7 @@ def folder_path if folder folder.full_name else - Folder.root_folders(self.context).first.try(:name) + Folder.root_folders(context).first.try(:name) end end @@ -1894,7 +1894,7 @@ def self.domain_namespace=(val) end def self.domain_namespace - self.current_namespace + current_namespace end def self.serialization_methods @@ -1964,9 +1964,9 @@ def self.dynamic_thumbnail_sizes end def create_dynamic_thumbnail(geometry_string) - tmp = self.create_temp_file + tmp = create_temp_file Attachment.unique_constraint_retry do - self.create_or_update_thumbnail(tmp, geometry_string, geometry_string) + create_or_update_thumbnail(tmp, geometry_string, geometry_string) end end @@ -2012,17 +2012,17 @@ def clone_url(url, duplicate_handling, check_quota, opts = {}) Attachment.clone_url_as_attachment(url, :attachment => self) if check_quota - self.save! # save to calculate attachment size, otherwise self.size is nil - if Attachment.over_quota?(opts[:quota_context] || self.context, self.size) + save! # save to calculate attachment size, otherwise self.size is nil + if Attachment.over_quota?(opts[:quota_context] || context, size) raise OverQuotaError, t(:over_quota, 'The downloaded file exceeds the quota.') end end self.file_state = 'available' - self.save! + save! # the UI only needs the id from here - opts[:progress]&.set_results({ id: self.id }) + opts[:progress]&.set_results({ id: id }) handle_duplicates(duplicate_handling || 'overwrite') nil # the rescue returns true if the file failed and is retryable, nil if successful @@ -2047,7 +2047,7 @@ def clone_url(url, duplicate_handling, check_quota, opts = {}) failed_retryable = true self.upload_error_message = t :upload_error_timeout, "The request timed out: %{url}", :url => url when OverQuotaError - self.upload_error_message = t :upload_error_over_quota, "file size exceeds quota limits: %{bytes} bytes", :bytes => self.size + self.upload_error_message = t :upload_error_over_quota, "file size exceeds quota limits: %{bytes} bytes", :bytes => size else failed_retryable = true self.upload_error_message = t :upload_error_unexpected, "An unknown error occurred downloading from %{url}", :url => url @@ -2055,11 +2055,11 @@ def clone_url(url, duplicate_handling, check_quota, opts = {}) end if opts[:progress] - opts[:progress].message = self.upload_error_message + opts[:progress].message = upload_error_message opts[:progress].fail! end - self.save! + save! failed_retryable end @@ -2125,10 +2125,10 @@ def copy_to_student_annotation_documents_folder(course) end def set_publish_state_for_usage_rights - self.locked = if self.context && - (!self.folder || !self.folder.for_submissions?) && - self.context.respond_to?(:usage_rights_required?) && self.context.usage_rights_required? - self.usage_rights.nil? + self.locked = if context && + (!folder || !folder.for_submissions?) && + context.respond_to?(:usage_rights_required?) && context.usage_rights_required? + usage_rights.nil? else false end diff --git a/app/models/auditors/active_record/course_record.rb b/app/models/auditors/active_record/course_record.rb index 3d04cb5a30658..d3298242a5d6e 100644 --- a/app/models/auditors/active_record/course_record.rb +++ b/app/models/auditors/active_record/course_record.rb @@ -47,7 +47,7 @@ def ar_attributes_from_event_stream(record) end def event_data - @_event_data ||= JSON.parse(self.data) + @_event_data ||= JSON.parse(data) end end end diff --git a/app/models/auditors/course.rb b/app/models/auditors/course.rb index 77509620c5be0..f3a65e4922fbb 100644 --- a/app/models/auditors/course.rb +++ b/app/models/auditors/course.rb @@ -141,70 +141,70 @@ def self.remove_empty_changes(changes) def self.record_created(course, user, changes, opts = {}) return unless course && changes - changes = self.remove_empty_changes(changes) + changes = remove_empty_changes(changes) return if changes.empty? - self.record(course, user, "created", changes, opts) + record(course, user, "created", changes, opts) end def self.record_updated(course, user, changes, opts = {}) return unless course && changes - changes = self.remove_empty_changes(changes) + changes = remove_empty_changes(changes) return if changes.empty? - self.record(course, user, 'updated', changes, opts) + record(course, user, 'updated', changes, opts) end def self.record_concluded(course, user, opts = {}) return unless course - self.record(course, user, 'concluded', {}, opts) + record(course, user, 'concluded', {}, opts) end def self.record_unconcluded(course, user, opts = {}) return unless course - self.record(course, user, 'unconcluded', {}, opts) + record(course, user, 'unconcluded', {}, opts) end def self.record_deleted(course, user, opts = {}) return unless course - self.record(course, user, 'deleted', {}, opts) + record(course, user, 'deleted', {}, opts) end def self.record_restored(course, user, opts = {}) return unless course - self.record(course, user, 'restored', {}, opts) + record(course, user, 'restored', {}, opts) end def self.record_published(course, user, opts = {}) return unless course - self.record(course, user, 'published', {}, opts) + record(course, user, 'published', {}, opts) end def self.record_claimed(course, user, opts = {}) return unless course - self.record(course, user, 'claimed', {}, opts) + record(course, user, 'claimed', {}, opts) end def self.record_copied(course, copy, user, opts = {}) return unless course && copy - copied_from = self.record(copy, user, 'copied_from', { copied_from: Shard.global_id_for(course) }, opts) - copied_to = self.record(course, user, 'copied_to', { copied_to: Shard.global_id_for(copy) }, opts) + copied_from = record(copy, user, 'copied_from', { copied_from: Shard.global_id_for(course) }, opts) + copied_to = record(course, user, 'copied_to', { copied_to: Shard.global_id_for(copy) }, opts) [copied_from, copied_to] end def self.record_reset(course, new_course, user, opts = {}) return unless course && new_course - reset_from = self.record(new_course, user, 'reset_from', { reset_from: Shard.global_id_for(course) }, opts) - reset_to = self.record(course, user, 'reset_to', { reset_to: Shard.global_id_for(new_course) }, opts) + reset_from = record(new_course, user, 'reset_from', { reset_from: Shard.global_id_for(course) }, opts) + reset_to = record(course, user, 'reset_to', { reset_to: Shard.global_id_for(new_course) }, opts) [reset_from, reset_to] end diff --git a/app/models/authentication_provider.rb b/app/models/authentication_provider.rb index a4f6ab13d1da9..b7b7d06b11f7f 100644 --- a/app/models/authentication_provider.rb +++ b/app/models/authentication_provider.rb @@ -151,9 +151,9 @@ def self.login_button? end def destroy - self.send(:remove_from_list_for_destroy) + send(:remove_from_list_for_destroy) self.workflow_state = 'deleted' - self.save! + save! enable_canvas_authentication delay_if_production.soft_delete_pseudonyms true @@ -167,9 +167,9 @@ def auth_password=(password) end def auth_decrypted_password - return nil unless self.auth_password_salt && self.auth_crypted_password + return nil unless auth_password_salt && auth_crypted_password - ::Canvas::Security.decrypt_password(self.auth_crypted_password, self.auth_password_salt, 'instructure_auth') + ::Canvas::Security.decrypt_password(auth_crypted_password, auth_password_salt, 'instructure_auth') end def auth_provider_filter @@ -368,7 +368,7 @@ def debug_set(key, value, overwrite: true) protected def statsd_prefix - "auth.account_#{Shard.global_id_for(account_id)}.config_#{self.global_id}" + "auth.account_#{Shard.global_id_for(account_id)}.config_#{global_id}" end private @@ -432,7 +432,7 @@ def enable_canvas_authentication end def debug_key(key) - ['auth_provider_debugging', self.global_id, key.to_s].cache_key + ['auth_provider_debugging', global_id, key.to_s].cache_key end def debug_expire diff --git a/app/models/authentication_provider/delegated.rb b/app/models/authentication_provider/delegated.rb index 3e2771a13401c..a9a6482abee62 100644 --- a/app/models/authentication_provider/delegated.rb +++ b/app/models/authentication_provider/delegated.rb @@ -22,9 +22,9 @@ class AuthenticationProvider::Delegated < AuthenticationProvider after_create :disable_open_registration def disable_open_registration - if self.account.open_registration? - self.account.settings[:open_registration] = false - self.account.save! + if account.open_registration? + account.settings[:open_registration] = false + account.save! end end diff --git a/app/models/authentication_provider/ldap.rb b/app/models/authentication_provider/ldap.rb index 1e0dd301e7ad2..06621b60becd5 100644 --- a/app/models/authentication_provider/ldap.rb +++ b/app/models/authentication_provider/ldap.rb @@ -36,7 +36,7 @@ def self.recognized_params SENSITIVE_PARAMS = [:auth_password].freeze def clear_last_timeout_failure - unless self.last_timeout_failure_changed? + unless last_timeout_failure_changed? self.last_timeout_failure = nil end end @@ -59,7 +59,7 @@ def auth_over_tls end def ldap_connection - raise "Not an LDAP config" unless self.auth_type == 'ldap' + raise "Not an LDAP config" unless auth_type == 'ldap' require 'net/ldap' args = {} @@ -74,10 +74,10 @@ def ldap_connection end ldap = Net::LDAP.new(args) - ldap.host = self.auth_host - ldap.port = self.auth_port - ldap.base = self.auth_base - ldap.auth self.auth_username, self.auth_decrypted_password + ldap.host = auth_host + ldap.port = auth_port + ldap.base = auth_base + ldap.auth auth_username, auth_decrypted_password ldap end @@ -93,7 +93,7 @@ def sanitized_ldap_login(login) end def ldap_filter(login = nil) - filter = self.auth_filter + filter = auth_filter filter = filter.gsub(/\{\{login\}\}/, sanitized_ldap_login(login)) if login filter end @@ -103,7 +103,7 @@ def ldap_filter=(new_filter) end def ldap_ip - Socket.getaddrinfo(self.auth_host, 'http', nil, Socket::SOCK_STREAM)[0][3] + Socket.getaddrinfo(auth_host, 'http', nil, Socket::SOCK_STREAM)[0][3] rescue SocketError nil end @@ -115,52 +115,52 @@ def auth_provider_filter def test_ldap_connection begin timeout(Setting.get('test_ldap_connection_timeout', '5').to_i) do - TCPSocket.open(self.auth_host, self.auth_port) + TCPSocket.open(auth_host, auth_port) end return true rescue SocketError - self.errors.add(:ldap_connection_test, t(:test_host_unknown, "Unknown host: %{host}", :host => self.auth_host)) + errors.add(:ldap_connection_test, t(:test_host_unknown, "Unknown host: %{host}", :host => auth_host)) rescue Timeout::Error - self.errors.add(:ldap_connection_test, t(:test_connection_timeout, "Timeout when connecting")) + errors.add(:ldap_connection_test, t(:test_connection_timeout, "Timeout when connecting")) rescue => e - self.errors.add(:ldap_connection_test, e.message) + errors.add(:ldap_connection_test, e.message) end false end def test_ldap_bind timeout(Setting.get('test_ldap_bind_timeout', '60').to_i) do - conn = self.ldap_connection + conn = ldap_connection unless (res = conn.bind) error = conn.get_operation_result - self.errors.add(:ldap_bind_test, "Error #{error.code}: #{error.message}") + errors.add(:ldap_bind_test, "Error #{error.code}: #{error.message}") end return res end rescue Timeout::Error - self.errors.add(:ldap_bind_test, t(:test_bind_timeout, "Timeout when binding")) + errors.add(:ldap_bind_test, t(:test_bind_timeout, "Timeout when binding")) false rescue => e - self.errors.add(:ldap_bind_test, t(:test_bind_failed, "Failed to bind with the following error: %{error}", :error => e.message)) + errors.add(:ldap_bind_test, t(:test_bind_failed, "Failed to bind with the following error: %{error}", :error => e.message)) false end def test_ldap_search Timeout.timeout(Setting.get('test_ldap_search_timeout', '60').to_i) do - conn = self.ldap_connection - filter = self.ldap_filter("canvas_ldap_test_user") + conn = ldap_connection + filter = ldap_filter("canvas_ldap_test_user") Net::LDAP::Filter.construct(filter) unless (res = conn.search { |s| break s }) error = conn.get_operation_result - self.errors.add(:ldap_search_test, "Error #{error.code}: #{error.message}") + errors.add(:ldap_search_test, "Error #{error.code}: #{error.message}") end return res.present? end rescue Timeout::Error - self.errors.add(:ldap_bind_test, t("Timeout when searching")) + errors.add(:ldap_bind_test, t("Timeout when searching")) false rescue => e - self.errors.add( + errors.add( :ldap_search_test, t(:test_search_failed, "Search failed with the following error: %{error}", :error => e) ) @@ -168,18 +168,18 @@ def test_ldap_search end def test_ldap_login(username, password) - ldap = self.ldap_connection - filter = self.ldap_filter(username) + ldap = ldap_connection + filter = ldap_filter(username) begin res = ldap.bind_as(:base => ldap.base, :filter => filter, :password => password) return true if res - self.errors.add( + errors.add( :ldap_login_test, t(:test_login_auth_failed, "Authentication failed") ) rescue Net::LDAP::LdapError => e - self.errors.add( + errors.add( :ldap_login_test, t(:test_login_auth_exception, "Exception on login: %{error}", :error => e) ) @@ -188,7 +188,7 @@ def test_ldap_login(username, password) end def failure_wait_time - ::Canvas.timeout_protection_error_ttl("ldap:#{self.global_id}") + ::Canvas.timeout_protection_error_ttl("ldap:#{global_id}") end def ldap_account_ids_to_send_to_statsd @@ -205,32 +205,32 @@ def ldap_bind_result(unique_id, password_plaintext) default_timeout = Setting.get('ldap_timelimit', 5.seconds.to_s).to_f timeout_options = { raise_on_timeout: true, fallback_timeout_length: default_timeout } - result = ::Canvas.timeout_protection("ldap:#{self.global_id}", timeout_options) do - ldap = self.ldap_connection - filter = self.ldap_filter(unique_id) + result = ::Canvas.timeout_protection("ldap:#{global_id}", timeout_options) do + ldap = ldap_connection + filter = ldap_filter(unique_id) ldap.bind_as(base: ldap.base, filter: filter, password: password_plaintext) end if should_send_to_statsd? InstStatsd::Statsd.increment("#{statsd_prefix}.ldap_#{result ? 'success' : 'failure'}", short_stat: "ldap_#{result ? 'success' : 'failure'}", - tags: { account_id: Shard.global_id_for(account_id), auth_provider_id: self.global_id }) + tags: { account_id: Shard.global_id_for(account_id), auth_provider_id: global_id }) end result rescue => e - ::Canvas::Errors.capture(e, { type: :ldap, account: self.account }, :warn) + ::Canvas::Errors.capture(e, { type: :ldap, account: account }, :warn) if e.is_a?(Timeout::Error) if should_send_to_statsd? InstStatsd::Statsd.increment("#{statsd_prefix}.ldap_timeout", short_stat: "ldap_timeout", - tags: { account_id: Shard.global_id_for(account_id), auth_provider_id: self.global_id }) + tags: { account_id: Shard.global_id_for(account_id), auth_provider_id: global_id }) end - self.update_attribute(:last_timeout_failure, Time.zone.now) + update_attribute(:last_timeout_failure, Time.zone.now) elsif should_send_to_statsd? InstStatsd::Statsd.increment("#{statsd_prefix}.ldap_error", short_stat: "ldap_error", - tags: { account_id: Shard.global_id_for(account_id), auth_provider_id: self.global_id }) + tags: { account_id: Shard.global_id_for(account_id), auth_provider_id: global_id }) end nil end diff --git a/app/models/authentication_provider/saml.rb b/app/models/authentication_provider/saml.rb index 4167883fe4b3e..d3fdae0153fc6 100644 --- a/app/models/authentication_provider/saml.rb +++ b/app/models/authentication_provider/saml.rb @@ -128,11 +128,11 @@ def auth_provider_filter end def entity_id - self.class.saml_default_entity_id_for_account(self.account, persist: !new_record?) + self.class.saml_default_entity_id_for_account(account, persist: !new_record?) end def set_saml_defaults - self.requested_authn_context = nil if self.requested_authn_context.blank? + self.requested_authn_context = nil if requested_authn_context.blank? end def validate_urls @@ -274,8 +274,8 @@ def populate_from_metadata(entity) self.identifier_format = SAML2::NameID::Format::UNSPECIFIED end - self.settings[:signing_certificates] = idp.signing_keys.filter_map(&:x509) - self.settings[:signing_keys] = idp.signing_keys.filter_map(&:key).map(&:to_s) + settings[:signing_certificates] = idp.signing_keys.filter_map(&:x509) + settings[:signing_keys] = idp.signing_keys.filter_map(&:key).map(&:to_s) case idp.want_authn_requests_signed? when true # use ||= to not overwrite a specific algorithm that has otherwise been diff --git a/app/models/big_blue_button_conference.rb b/app/models/big_blue_button_conference.rb index fcc0fc91de44a..5780717cd6715 100644 --- a/app/models/big_blue_button_conference.rb +++ b/app/models/big_blue_button_conference.rb @@ -121,8 +121,8 @@ def xml_to_value(node) def initiate_conference return conference_key if conference_key && !retouch? - unless self.conference_key - self.conference_key = "instructure_#{self.feed_code}".gsub(/[^a-zA-Z0-9_]/, "_") + unless conference_key + self.conference_key = "instructure_#{feed_code}".gsub(/[^a-zA-Z0-9_]/, "_") chars = ('a'..'z').to_a + ('0'..'9').to_a # create user/admin passwords for this conference. we may want to show # the admin passwords in the ui in case moderators need them for any @@ -153,14 +153,14 @@ def initiate_conference end def recording_ready_user - if self.grants_right?(self.user, :create) - "#{self.user['name']} <#{self.user.email}>" + if grants_right?(user, :create) + "#{user['name']} <#{user.email}>" end end def recording_ready_url(current_host = nil) polymorphic_url([:api_v1, context, :conferences, :recording_ready], - conference_id: self.id, + conference_id: id, protocol: HostUrl.protocol, host: HostUrl.context_host(context, current_host)) end @@ -260,7 +260,7 @@ def self.fetch_and_preload_recordings(conferences, use_fallback_config: false) def use_fallback_config? # use the fallback config (if possible) if it wasn't created with the current config self.class.config[:use_fallback] && - self.settings[:domain] != self.class.config[:domain] + settings[:domain] != self.class.config[:domain] end private diff --git a/app/models/bookmark_service.rb b/app/models/bookmark_service.rb index b9d0a5756e77e..35ec3f9f2add3 100644 --- a/app/models/bookmark_service.rb +++ b/app/models/bookmark_service.rb @@ -31,7 +31,7 @@ def post_bookmark(opts) description = opts[:comments] || "" tags = opts[:tags] || ['instructure'] begin - case self.service + case service when 'delicious' delicious_post_bookmark(self, url, title, description, tags) when 'diigo' @@ -43,7 +43,7 @@ def post_bookmark(opts) end def find_bookmarks(query) - if self.service == 'diigo' + if service == 'diigo' last_get = Rails.cache.fetch('last_diigo_lookup') { Time.now - 60 } if Time.now - last_get < 8 Rails.cache.write('last_diigo_lookup', Time.now) diff --git a/app/models/bounce_notification_processor.rb b/app/models/bounce_notification_processor.rb index ffa84ce6b00d5..b9b063ea52c26 100644 --- a/app/models/bounce_notification_processor.rb +++ b/app/models/bounce_notification_processor.rb @@ -34,14 +34,14 @@ def self.config end def self.enabled? - !!self.config + !!config end def self.process - bounce = self.new + bounce = new key = 'bounce_processors_for_region_' + bounce.config[:region].to_s num_of_jobs = Setting.get(key, '0').to_i - num_of_jobs.times { self.new.delay(priority: Delayed::LOW_PRIORITY).process } + num_of_jobs.times { new.delay(priority: Delayed::LOW_PRIORITY).process } bounce.process end diff --git a/app/models/brand_config.rb b/app/models/brand_config.rb index 58adbf80a608a..aa8cf36b2aec1 100644 --- a/app/models/brand_config.rb +++ b/app/models/brand_config.rb @@ -72,7 +72,7 @@ def self.find_cached_by_md5(md5) end def clear_cache - self.shard.activate do + shard.activate do self.class.connection.after_transaction_commit do MultiCache.delete(self.class.cache_key_for_md5(shard.id, md5)) end @@ -109,17 +109,17 @@ def chain_of_ancestor_configs end def clone_with_new_parent(new_parent_md5) - attrs = self.attributes.with_indifferent_access.slice(*BrandConfig::ATTRS_TO_INCLUDE_IN_MD5) + attrs = attributes.with_indifferent_access.slice(*BrandConfig::ATTRS_TO_INCLUDE_IN_MD5) attrs[:parent_md5] = new_parent_md5 BrandConfig.for(attrs) end def dup? - BrandConfig.where(md5: self.md5).exists? + BrandConfig.where(md5: md5).exists? end def save_unless_dup! - self.save! unless dup? + save! unless dup? end def to_json(*args) diff --git a/app/models/calendar_event.rb b/app/models/calendar_event.rb index 1aba3c45fdcc4..9d9e1aadb520b 100644 --- a/app/models/calendar_event.rb +++ b/app/models/calendar_event.rb @@ -37,7 +37,7 @@ class CalendarEvent < ActiveRecord::Base attr_accessor :cancel_reason, :imported sanitize_field :description, CanvasSanitize::SANITIZE - copy_authorized_links(:description) { [self.effective_context, nil] } + copy_authorized_links(:description) { [effective_context, nil] } include Workflow @@ -225,11 +225,11 @@ def validate_context! attr_reader :validate_context def default_values - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" - self.title ||= (self.context_type.to_s + " Event") rescue "Event" + self.context_code = "#{context_type.underscore}_#{context_id}" + self.title ||= (context_type.to_s + " Event") rescue "Event" populate_missing_dates - populate_all_day_flag unless self.imported + populate_all_day_flag unless imported if parent_event populate_with_parent_event @@ -239,16 +239,16 @@ def default_values end protected :default_values - def set_root_account(ctx = self.context) + def set_root_account(ctx = context) if ctx.respond_to?(:root_account) self.root_account = ctx.root_account # course, section, group else case ctx when User - if self.effective_context.is_a?(User) + if effective_context.is_a?(User) self.root_account_id = 0 else - self.set_root_account(self.effective_context) + set_root_account(effective_context) end when AppointmentGroup self.root_account = context.context&.root_account @@ -257,7 +257,7 @@ def set_root_account(ctx = self.context) end def child_event_participants_scope - self.shard.activate do + shard.activate do # user is set directly, or context is user User.where("id IN (#{child_events.where.not(:user_id => nil).select(:user_id).to_sql} @@ -293,7 +293,7 @@ def populate_with_parent_event # Populate the start and end dates if they are not set, or if they are invalid def populate_missing_dates - self.end_at ||= self.start_at + self.end_at ||= start_at self.start_at ||= self.end_at if self.start_at && self.end_at && self.end_at < self.start_at self.end_at = self.start_at @@ -303,14 +303,14 @@ def populate_missing_dates def populate_all_day_flag # If the all day flag has been changed to all day, set the times to 00:00 - if self.all_day_changed? && self.all_day? + if all_day_changed? && all_day? self.start_at = zoned_start_at.beginning_of_day rescue nil self.end_at = zoned_end_at.beginning_of_day rescue nil - elsif self.start_at_changed? || self.end_at_changed? || Canvas::Plugin.value_to_boolean(self.remove_child_events) + elsif start_at_changed? || end_at_changed? || Canvas::Plugin.value_to_boolean(remove_child_events) self.all_day = self.start_at && self.start_at == self.end_at && zoned_start_at.strftime("%H:%M") == '00:00' end - if self.all_day && (!self.all_day_date || self.start_at_changed? || self.all_day_date_changed?) + if all_day && (!all_day_date || start_at_changed? || all_day_date_changed?) self.start_at = zoned_start_at.beginning_of_day rescue nil self.end_at = zoned_end_at.beginning_of_day rescue nil self.all_day_date = (zoned_start_at.to_date rescue nil) @@ -321,12 +321,12 @@ def populate_all_day_flag # Localized start_at def zoned_start_at self.start_at && ActiveSupport::TimeWithZone.new(self.start_at.utc, - ((ActiveSupport::TimeZone.new(self.time_zone_edited) rescue nil) || Time.zone)) + ((ActiveSupport::TimeZone.new(time_zone_edited) rescue nil) || Time.zone)) end def zoned_end_at self.end_at && ActiveSupport::TimeWithZone.new(self.end_at.utc, - ((ActiveSupport::TimeZone.new(self.time_zone_edited) rescue nil) || Time.zone)) + ((ActiveSupport::TimeZone.new(time_zone_edited) rescue nil) || Time.zone)) end CASCADED_ATTRIBUTES = [ @@ -609,21 +609,21 @@ def update_matching_days=(update) end def all_day - read_attribute(:all_day) || (self.new_record? && self.start_at && self.start_at == self.end_at && self.start_at.strftime("%H:%M") == '00:00') + read_attribute(:all_day) || (new_record? && self.start_at && self.start_at == self.end_at && self.start_at.strftime("%H:%M") == '00:00') end def to_atom(opts = {}) extend ApplicationHelper Atom::Entry.new do |entry| entry.title = t(:feed_item_title, "Calendar Event: %{event_title}", :event_title => self.title) unless opts[:include_context] - entry.title = t(:feed_item_title_with_context, "Calendar Event, %{course_or_account_name}: %{event_title}", :course_or_account_name => self.context.name, :event_title => self.title) if opts[:include_context] - entry.authors << Atom::Person.new(:name => self.context.name) - entry.updated = self.updated_at.utc - entry.published = self.created_at.utc + entry.title = t(:feed_item_title_with_context, "Calendar Event, %{course_or_account_name}: %{event_title}", :course_or_account_name => context.name, :event_title => self.title) if opts[:include_context] + entry.authors << Atom::Person.new(:name => context.name) + entry.updated = updated_at.utc + entry.published = created_at.utc entry.links << Atom::Link.new(:rel => 'alternate', - :href => "http://#{HostUrl.context_host(self.context)}/#{context_url_prefix}/calendar?month=#{self.start_at.strftime("%m") rescue ""}&year=#{self.start_at.strftime("%Y") rescue ""}#calendar_event_#{self.id}") - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime("%Y-%m-%d")}:/calendar_events/#{self.feed_code}_#{self.start_at.strftime("%Y-%m-%d-%H-%M") rescue "none"}_#{self.end_at.strftime("%Y-%m-%d-%H-%M") rescue "none"}" - entry.content = Atom::Content::Html.new("#{datetime_string(self.start_at, self.end_at)}
#{self.description}") + :href => "http://#{HostUrl.context_host(context)}/#{context_url_prefix}/calendar?month=#{self.start_at.strftime("%m") rescue ""}&year=#{self.start_at.strftime("%Y") rescue ""}#calendar_event_#{id}") + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime("%Y-%m-%d")}:/calendar_events/#{feed_code}_#{self.start_at.strftime("%Y-%m-%d-%H-%M") rescue "none"}_#{self.end_at.strftime("%Y-%m-%d-%H-%M") rescue "none"}" + entry.content = Atom::Content::Html.new("#{datetime_string(self.start_at, self.end_at)}
#{description}") end end @@ -639,7 +639,7 @@ def self.max_visible_calendars end set_policy do - given { |user, session| self.context.grants_right?(user, session, :read) } # students.include?(user) } + given { |user, session| context.grants_right?(user, session, :read) } # students.include?(user) } can :read given do |user, session| @@ -665,13 +665,13 @@ def self.max_visible_calendars } can :reserve - given { |user, session| self.context.grants_right?(user, session, :manage_calendar) } # admins.include?(user) } + given { |user, session| context.grants_right?(user, session, :manage_calendar) } # admins.include?(user) } can :read and can :create - given { |user, session| (!locked? || context.is_a?(AppointmentGroup)) && !deleted? && self.context.grants_right?(user, session, :manage_calendar) } # admins.include?(user) } + given { |user, session| (!locked? || context.is_a?(AppointmentGroup)) && !deleted? && context.grants_right?(user, session, :manage_calendar) } # admins.include?(user) } can :update and can :update_content - given { |user, session| !deleted? && self.context.grants_right?(user, session, :manage_calendar) } + given { |user, session| !deleted? && context.grants_right?(user, session, :manage_calendar) } can :delete end diff --git a/app/models/canvadoc.rb b/app/models/canvadoc.rb index 946673285268b..79945f05c8219 100644 --- a/app/models/canvadoc.rb +++ b/app/models/canvadoc.rb @@ -43,7 +43,7 @@ def upload(opts = {}) self.document_id = response['id'] self.process_state = response['status'] self.has_annotations = opts[:annotatable] - self.save! + save! elsif response.nil? raise UploadTimeout, "no response received (request timed out?)" else @@ -52,9 +52,9 @@ def upload(opts = {}) end def submissions - self.canvadocs_submissions - .preload(submission: :assignment) - .map(&:submission) + canvadocs_submissions + .preload(submission: :assignment) + .map(&:submission) end def available? diff --git a/app/models/canvadocs_annotation_context.rb b/app/models/canvadocs_annotation_context.rb index 557a386040032..11eb66d433739 100644 --- a/app/models/canvadocs_annotation_context.rb +++ b/app/models/canvadocs_annotation_context.rb @@ -63,7 +63,7 @@ class CanvadocsAnnotationContext < ApplicationRecord end def draft? - self.submission_attempt.nil? + submission_attempt.nil? end def set_launch_id @@ -71,6 +71,6 @@ def set_launch_id end def set_root_account_id - self.root_account_id ||= self.submission&.root_account_id + self.root_account_id ||= submission&.root_account_id end end diff --git a/app/models/collaboration.rb b/app/models/collaboration.rb index 48bbfeb276330..52e8cd09f200b 100644 --- a/app/models/collaboration.rb +++ b/app/models/collaboration.rb @@ -55,15 +55,15 @@ class Collaboration < ActiveRecord::Base end on_create_send_to_streams do - [self.user_id] + self.collaborators.map(&:user_id) + [user_id] + collaborators.map(&:user_id) end set_policy do given { |user| user && - !self.new_record? && - (self.user_id == user.id || - self.users.include?(user) || + !new_record? && + (user_id == user.id || + users.include?(user) || Collaborator .joins("INNER JOIN #{GroupMembership.quoted_table_name} ON collaborators.group_id = group_memberships.group_id") .where('collaborators.group_id IS NOT NULL AND @@ -72,15 +72,15 @@ class Collaboration < ActiveRecord::Base } can :read - given { |user, session| self.context.grants_right?(user, session, :create_collaborations) } + given { |user, session| context.grants_right?(user, session, :create_collaborations) } can :create - given { |user, session| self.context.grants_right?(user, session, :manage_content) } + given { |user, session| context.grants_right?(user, session, :manage_content) } can :read and can :update and can :delete given { |user, session| - user && self.user_id == user.id && - self.context.grants_right?(user, session, :create_collaborations) + user && user_id == user.id && + context.grants_right?(user, session, :create_collaborations) } can :read and can :update and can :delete end @@ -212,14 +212,14 @@ def restore # # Returns nothing. def include_author_as_collaborator - return unless self.user.present? + return unless user.present? - author = collaborators.where(:user_id => self.user_id).first + author = collaborators.where(:user_id => user_id).first unless author collaborator = Collaborator.new(:collaboration => self) - collaborator.user_id = self.user_id - collaborator.authorized_service_user_id = authorized_service_user_id_for(self.user) + collaborator.user_id = user_id + collaborator.authorized_service_user_id = authorized_service_user_id_for(user) collaborator.save end end @@ -238,7 +238,7 @@ def style_class # # Returns a comma-seperated list of collaborator user IDs. def collaborator_ids - self.collaborators.pluck(:user_id).join(',') + collaborators.pluck(:user_id).join(',') end # Internal: Create the collaboration document in the remote service. @@ -302,7 +302,7 @@ def assign_uuid # # Returns a context code. def set_context_code - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" + self.context_code = "#{context_type.underscore}_#{context_id}" rescue NoMethodError nil end @@ -324,7 +324,7 @@ def update_user_collaborators(users) users_to_remove.uniq! end # make real user objects, instead of just ids, cause that's what this code expects - users_to_remove.reject! { |id| id == self.user.id } + users_to_remove.reject! { |id| id == user.id } users_to_remove = users_to_remove.map { |id| User.send(:instantiate, 'id' => id) } remove_users_from_document(users_to_remove) end diff --git a/app/models/collaborator.rb b/app/models/collaborator.rb index 0d8c7fa7307ed..f177e609d6061 100644 --- a/app/models/collaborator.rb +++ b/app/models/collaborator.rb @@ -32,16 +32,16 @@ def course_broadcast_data set_broadcast_policy do |p| p.dispatch :collaboration_invitation p.to { - users = self.group_id.nil? ? [self.user] : self.group.users - [self.user] - if self.context.is_a?(Course) - if !self.context.workflow_state.in?(['available', 'completed']) + users = group_id.nil? ? [user] : group.users - [user] + if context.is_a?(Course) + if !context.workflow_state.in?(['available', 'completed']) users = [] # do not send notifications to any users if the course is unpublished else - enrolled_user_ids = self.context.enrollments.active_by_date.where(:user_id => users).pluck(:user_id).to_set + enrolled_user_ids = context.enrollments.active_by_date.where(:user_id => users).pluck(:user_id).to_set users = users.select { |u| enrolled_user_ids.include?(u.id) } end end - if self.collaboration.collaboration_type == 'google_docs' + if collaboration.collaboration_type == 'google_docs' users.map(&:gmail_channel) else users diff --git a/app/models/comment_bank_item.rb b/app/models/comment_bank_item.rb index ccc872973e8e6..f62864f7b0ea3 100644 --- a/app/models/comment_bank_item.rb +++ b/app/models/comment_bank_item.rb @@ -32,7 +32,7 @@ class CommentBankItem < ActiveRecord::Base given { |user| self.user == user } can :delete and can :read and can :update - given { |user, session| self.course.grants_right?(user, session, :manage_grades) } + given { |user, session| course.grants_right?(user, session, :manage_grades) } can :create end end diff --git a/app/models/communication_channel.rb b/app/models/communication_channel.rb index b806cb2fc9fed..7c9ed7ce5dce4 100644 --- a/app/models/communication_channel.rb +++ b/app/models/communication_channel.rb @@ -68,13 +68,13 @@ class CommunicationChannel < ActiveRecord::Base def under_user_cc_limit max_ccs = Setting.get('max_ccs_per_user', '100').to_i - if self.user.communication_channels.limit(max_ccs + 1).count > max_ccs - self.errors.add(:user_id, 'user communication_channels limit exceeded') + if user.communication_channels.limit(max_ccs + 1).count > max_ccs + errors.add(:user_id, 'user communication_channels limit exceeded') end end def clear_user_email_cache - self.user.clear_email_cache! if self.path_type == TYPE_EMAIL + user.clear_email_cache! if path_type == TYPE_EMAIL end def self.country_codes @@ -196,16 +196,16 @@ def pseudonym p.whenever { |record| @send_confirmation and (record.workflow_state == 'active' || - (record.workflow_state == 'unconfirmed' and (self.user.pre_registered? || self.user.creation_pending?))) and - self.path_type == TYPE_EMAIL + (record.workflow_state == 'unconfirmed' and (user.pre_registered? || user.creation_pending?))) and + path_type == TYPE_EMAIL } p.dispatch :confirm_email_communication_channel p.to { self } p.whenever { |record| @send_confirmation and - record.workflow_state == 'unconfirmed' and self.user.registered? and - self.path_type == TYPE_EMAIL + record.workflow_state == 'unconfirmed' and user.registered? and + path_type == TYPE_EMAIL } p.data { { @@ -216,15 +216,15 @@ def pseudonym p.dispatch :merge_email_communication_channel p.to { self } - p.whenever { @send_merge_notification && self.path_type == TYPE_EMAIL } + p.whenever { @send_merge_notification && path_type == TYPE_EMAIL } p.dispatch :confirm_sms_communication_channel p.to { self } p.whenever { |record| @send_confirmation and record.workflow_state == 'unconfirmed' and - (self.path_type == TYPE_SMS or self.path_type == TYPE_SLACK) and - !self.user.creation_pending? + (path_type == TYPE_SMS or path_type == TYPE_SLACK) and + !user.creation_pending? } p.data { { @@ -239,7 +239,7 @@ def uniqueness_of_path return if retired? return unless user_id - self.shard.activate do + shard.activate do # ^ if we create a new CC record while on another shard # and try to check the validity OUTSIDE the save path # (cc.valid?) this needs to switch to the shard where we'll @@ -249,7 +249,7 @@ def uniqueness_of_path scope = scope.where("id<>?", id) end if scope.exists? - self.errors.add(:path, :taken, :value => path) + errors.add(:path, :taken, :value => path) end end end @@ -257,11 +257,11 @@ def uniqueness_of_path def validate_email # this is not perfect and will allow for invalid emails, but it mostly works. # This pretty much allows anything with an "@" - self.errors.add(:email, :invalid, value: path) unless EmailAddressValidator.valid?(path) + errors.add(:email, :invalid, value: path) unless EmailAddressValidator.valid?(path) end def not_otp_communication_channel - self.errors.add(:workflow_state, "Can't remove a user's SMS that is used for one time passwords") if self.id == self.user.otp_communication_channel_id + errors.add(:workflow_state, "Can't remove a user's SMS that is used for one time passwords") if id == user.otp_communication_channel_id end # Public: Build the url where this record can be confirmed. @@ -289,54 +289,54 @@ def imported? # Return the 'path' for simple communication channel types like email and sms. # For Twitter, return the user's configured user_name for the service. def path_description - case self.path_type + case path_type when TYPE_TWITTER - res = self.user.user_services.for_service(TYPE_TWITTER).first.service_user_name rescue nil + res = user.user_services.for_service(TYPE_TWITTER).first.service_user_name rescue nil res ||= t :default_twitter_handle, 'Twitter Handle' res when TYPE_PUSH t 'For All Devices' else - self.path + path end end def forgot_password! - return if Rails.cache.read(['recent_password_reset', self.global_id].cache_key) == true + return if Rails.cache.read(['recent_password_reset', global_id].cache_key) == true @request_password = true - Rails.cache.write(['recent_password_reset', self.global_id].cache_key, true, expires_in: Setting.get('resend_password_reset_time', 5).to_f.minutes) + Rails.cache.write(['recent_password_reset', global_id].cache_key, true, expires_in: Setting.get('resend_password_reset_time', 5).to_f.minutes) set_confirmation_code(true, Setting.get('password_reset_token_expiration_minutes', '120').to_i.minutes.from_now) - self.save! + save! @request_password = false end def confirmation_limit_reached - self.confirmation_sent_count > 2 + confirmation_sent_count > 2 end def send_confirmation!(root_account) - if self.confirmation_limit_reached || bouncing? + if confirmation_limit_reached || bouncing? return end - self.confirmation_sent_count = self.confirmation_sent_count + 1 + self.confirmation_sent_count = confirmation_sent_count + 1 @send_confirmation = true @root_account = root_account - self.save! + save! @root_account = nil @send_confirmation = false end def send_merge_notification! @send_merge_notification = true - self.save! + save! @send_merge_notification = false end def send_otp_via_sms_gateway!(message) - m = self.messages.temp_record - m.to = self.path + m = messages.temp_record + m.to = path m.body = message Mailer.deliver(Mailer.create_message(m)) end @@ -368,7 +368,7 @@ def send_otp!(code, account = nil) # confirmation code in place. def set_confirmation_code(reset = false, expires_at = nil) self.confirmation_code = nil if reset - self.confirmation_code ||= if self.path_type == TYPE_EMAIL || self.path_type.nil? + self.confirmation_code ||= if path_type == TYPE_EMAIL || path_type.nil? CanvasSlug.generate(nil, 25) else CanvasSlug.generate @@ -404,8 +404,8 @@ def self.all_ordered_for_display(user) # Add twitter and yo (in that order) if the user's account is setup for them. rank_order << TYPE_TWITTER if twitter_service rank_order << TYPE_SLACK if user.associated_root_accounts.any? { |a| a.settings[:encrypted_slack_key] } - self.unretired.where(communication_channels: { path_type: rank_order }) - .order(Arel.sql("#{self.rank_sql(rank_order, 'communication_channels.path_type')} ASC, communication_channels.position asc")).to_a + unretired.where(communication_channels: { path_type: rank_order }) + .order(Arel.sql("#{rank_sql(rank_order, 'communication_channels.path_type')} ASC, communication_channels.position asc")).to_a end scope :in_state, lambda { |state| where(:workflow_state => state.to_s) } @@ -417,10 +417,10 @@ def self.all_ordered_for_display(user) # only ever true for Account.default # see build_pseudonym_for_email in app/views/profile/_ways_to_contact.html.erb def consider_building_pseudonym - if self.build_pseudonym_on_confirm && self.active? + if build_pseudonym_on_confirm && active? self.build_pseudonym_on_confirm = false - pseudonym = Account.default.pseudonyms.build(unique_id: self.path, user: self.user) - existing_pseudonym = Account.default.pseudonyms.active.where(user_id: self.user).take + pseudonym = Account.default.pseudonyms.build(unique_id: path, user: user) + existing_pseudonym = Account.default.pseudonyms.active.where(user_id: user).take if existing_pseudonym pseudonym.password_salt = existing_pseudonym.password_salt pseudonym.crypted_password = existing_pseudonym.crypted_password @@ -433,13 +433,13 @@ def consider_building_pseudonym alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'retired' - self.save + save end workflow do state :unconfirmed do event :confirm, :transitions_to => :active do - self.set_confirmation_code + set_confirmation_code end event :retire, :transitions_to => :retired end @@ -484,12 +484,12 @@ def self.associated_shards(_path) def merge_candidates(break_on_first_found = false) return [] if path_type == 'push' - shards = self.class.associated_shards(self.path) if Enrollment.cross_shard_invitations? - shards ||= [self.shard] - scope = CommunicationChannel.active.by_path(self.path).of_type(self.path_type) + shards = self.class.associated_shards(path) if Enrollment.cross_shard_invitations? + shards ||= [shard] + scope = CommunicationChannel.active.by_path(path).of_type(path_type) merge_candidates = {} Shard.with_each_shard(shards) do - scope = scope.shard(Shard.current).where("user_id<>?", self.user_id) + scope = scope.shard(Shard.current).where("user_id<>?", user_id) limit = Setting.get("merge_candidate_search_limit", "100").to_i ccs = scope.preload(:user).limit(limit + 1).to_a @@ -511,32 +511,32 @@ def has_merge_candidates? end def bouncing? - self.bounce_count >= RETIRE_THRESHOLD + bounce_count >= RETIRE_THRESHOLD end def was_bouncing? - old_bounce_count = self.previous_changes[:bounce_count].try(:first) - old_bounce_count ||= self.bounce_count + old_bounce_count = previous_changes[:bounce_count].try(:first) + old_bounce_count ||= bounce_count old_bounce_count >= RETIRE_THRESHOLD end def reset_bounce_count! self.bounce_count = 0 - self.save! + save! end def was_retired? - old_workflow_state = self.previous_changes[:workflow_state].try(:first) - old_workflow_state ||= self.workflow_state + old_workflow_state = previous_changes[:workflow_state].try(:first) + old_workflow_state ||= workflow_state old_workflow_state.to_s == 'retired' end def check_if_bouncing_changed if retired? - self.user.update_bouncing_channel_message!(self) if !was_retired? && was_bouncing? + user.update_bouncing_channel_message!(self) if !was_retired? && was_bouncing? else if (was_retired? && bouncing?) || (was_bouncing? != bouncing?) - self.user.update_bouncing_channel_message!(self) + user.update_bouncing_channel_message!(self) end end end diff --git a/app/models/conditional_release/assignment_set_action.rb b/app/models/conditional_release/assignment_set_action.rb index 722062ea75231..2c63825952abc 100644 --- a/app/models/conditional_release/assignment_set_action.rb +++ b/app/models/conditional_release/assignment_set_action.rb @@ -42,7 +42,7 @@ def set_root_account_id def self.current_assignments(student_id_or_ids, sets = nil) conditions = { student_id: student_id_or_ids } conditions[:assignment_set] = sets if sets - self.where(id: self.latest.where(conditions), action: 'assign') + where(id: latest.where(conditions), action: 'assign') end def self.create_from_sets(assigned, unassigned, opts = {}) diff --git a/app/models/conditional_release/assignment_set_association.rb b/app/models/conditional_release/assignment_set_association.rb index d21c192d14e2f..99414f295c675 100644 --- a/app/models/conditional_release/assignment_set_association.rb +++ b/app/models/conditional_release/assignment_set_association.rb @@ -42,10 +42,10 @@ def set_root_account_id end def clear_caches - if self.saved_change_to_deleted_at? && self.assignment.deleted? + if saved_change_to_deleted_at? && assignment.deleted? # normally this will be cleared by the rule, but not after assignment deletion self.class.connection.after_transaction_commit do - self.assignment.context.clear_cache_key(:conditional_release) + assignment.context.clear_cache_key(:conditional_release) end end end @@ -55,14 +55,14 @@ def clear_caches private def not_trigger - r = self.rule || self.assignment_set.scoring_range.rule # may not be saved yet + r = rule || assignment_set.scoring_range.rule # may not be saved yet if assignment_id == r.trigger_assignment_id errors.add(:assignment_id, "can't match rule trigger_assignment_id") end end def assignment_in_same_course - r = self.rule || self.assignment_set.scoring_range.rule # may not be saved yet + r = rule || assignment_set.scoring_range.rule # may not be saved yet if assignment_id_changed? && assignment&.context_id != r.course_id errors.add(:assignment_id, "invalid assignment") end diff --git a/app/models/conditional_release/rule.rb b/app/models/conditional_release/rule.rb index 306870d768de2..c17ecff336b11 100644 --- a/app/models/conditional_release/rule.rb +++ b/app/models/conditional_release/rule.rb @@ -75,8 +75,8 @@ def assignment_sets_for_score(score) def clear_caches self.class.connection.after_transaction_commit do - self.trigger_assignment.clear_cache_key(:conditional_release) - self.course.clear_cache_key(:conditional_release) + trigger_assignment.clear_cache_key(:conditional_release) + course.clear_cache_key(:conditional_release) end end @@ -84,7 +84,7 @@ def self.is_trigger_assignment?(assignment) # i'm only using the cache key currently for this one case but i figure it can be extended to handle caching around all rule data fetching RequestCache.cache('conditional_release_is_trigger', assignment) do Rails.cache.fetch_with_batched_keys('conditional_release_is_trigger', batch_object: assignment, batched_keys: :conditional_release) do - assignment.shard.activate { self.active.where(:trigger_assignment_id => assignment).exists? } + assignment.shard.activate { active.where(:trigger_assignment_id => assignment).exists? } end end end diff --git a/app/models/conditional_release/service.rb b/app/models/conditional_release/service.rb index 8c5c5c594b547..741258b51d469 100644 --- a/app/models/conditional_release/service.rb +++ b/app/models/conditional_release/service.rb @@ -25,7 +25,7 @@ class Service private_class_method :new def self.env_for(context, user = nil, session: nil, assignment: nil, includes: []) - enabled = self.enabled_in_context?(context) + enabled = enabled_in_context?(context) env = { CONDITIONAL_RELEASE_SERVICE_ENABLED: enabled } diff --git a/app/models/content_export.rb b/app/models/content_export.rb index c71691067a8b9..0a3bcf2584691 100644 --- a/app/models/content_export.rb +++ b/app/models/content_export.rb @@ -84,27 +84,27 @@ def send_notification? set_policy do # file managers (typically course admins) can read all course exports (not zip or user-data exports) given do |user, session| - self.context.grants_any_right?(user, session, *RoleOverride::GRANULAR_FILE_PERMISSIONS) && - [ZIP, USER_DATA].exclude?(self.export_type) + context.grants_any_right?(user, session, *RoleOverride::GRANULAR_FILE_PERMISSIONS) && + [ZIP, USER_DATA].exclude?(export_type) end can :read # admins can create exports of any type - given { |user, session| self.context.grants_right?(user, session, :read_as_admin) } + given { |user, session| context.grants_right?(user, session, :read_as_admin) } can :create # admins can read any export they created - given { |user, session| self.user == user && self.context.grants_right?(user, session, :read_as_admin) } + given { |user, session| self.user == user && context.grants_right?(user, session, :read_as_admin) } can :read # all users can read zip/user data exports they created (in contexts they retain read permission) # NOTE: other exports may be created on their behalf that they do *not* have direct access to; # e.g. a common cartridge export created under the hood when a student creates a web zip export - given { |user, session| self.user == user && [ZIP, USER_DATA].include?(self.export_type) && self.context.grants_right?(user, session, :read) } + given { |user, session| self.user == user && [ZIP, USER_DATA].include?(export_type) && context.grants_right?(user, session, :read) } can :read # non-admins can create zip or user-data exports, but not other types - given { |user, session| [ZIP, USER_DATA].include?(self.export_type) && self.context.grants_right?(user, session, :read) } + given { |user, session| [ZIP, USER_DATA].include?(export_type) && context.grants_right?(user, session, :read) } can :create # users can read exports that are shared with them @@ -113,20 +113,20 @@ def send_notification? end def set_global_identifiers - self.global_identifiers = can_use_global_identifiers? if CC_EXPORT_TYPES.include?(self.export_type) + self.global_identifiers = can_use_global_identifiers? if CC_EXPORT_TYPES.include?(export_type) end def can_use_global_identifiers? # use global identifiers if no other cc export from this course has used local identifiers # i.e. all exports from now on should try to use global identifiers # unless there's a risk of not matching up with a previous export - !self.context.content_exports.where(:export_type => CC_EXPORT_TYPES, :global_identifiers => false).exists? + !context.content_exports.where(:export_type => CC_EXPORT_TYPES, :global_identifiers => false).exists? end def quizzes_next? return false unless context.feature_enabled?(:quizzes_next) - export_type == QUIZZES2 || self.settings[:quizzes2].present? + export_type == QUIZZES2 || settings[:quizzes2].present? end def new_quizzes_page_enabled? @@ -136,7 +136,7 @@ def new_quizzes_page_enabled? def export(opts = {}) save if capture_job_id - self.shard.activate do + shard.activate do opts = opts.with_indifferent_access case export_type when ZIP @@ -158,28 +158,28 @@ def capture_job_id job = Delayed::Worker.current_job return false unless job - self.settings[:job_id] = job.id + settings[:job_id] = job.id true end def reset_and_start_job_progress - self.job_progress.try :reset! - self.job_progress.try :start! + job_progress.try :reset! + job_progress.try :start! end def mark_exporting self.workflow_state = 'exporting' - self.save + save end def mark_exported - self.job_progress.try :complete! + job_progress.try :complete! self.workflow_state = 'exported' end def mark_failed self.workflow_state = 'failed' - self.job_progress.fail! if self.job_progress&.queued? || self.job_progress&.running? + job_progress.fail! if job_progress&.queued? || job_progress&.running? end def fail_with_error!(exception_or_info = nil, error_message: I18n.t('Unexpected error while performing export')) @@ -196,7 +196,7 @@ def export_course(opts = {}) @cc_exporter = CC::CCExporter.new(self, opts.merge({ :for_course_copy => for_course_copy? })) if @cc_exporter.export self.progress = 100 - self.job_progress.try :complete! + job_progress.try :complete! self.workflow_state = if for_course_copy? 'exported_for_course_copy' else @@ -209,7 +209,7 @@ def export_course(opts = {}) add_error("Error running course export.", $ERROR_INFO) mark_failed ensure - self.save + save epub_export.try(:mark_exported) || true end end @@ -217,9 +217,9 @@ def export_course(opts = {}) def export_user_data(**) mark_exporting begin - self.job_progress.try :start! + job_progress.try :start! - if (exported_attachment = Exporters::UserDataExporter.create_user_data_export(self.context)) + if (exported_attachment = Exporters::UserDataExporter.create_user_data_export(context)) self.attachment = exported_attachment self.progress = 100 mark_exported @@ -228,14 +228,14 @@ def export_user_data(**) add_error("Error running user_data export.", $ERROR_INFO) mark_failed ensure - self.save + save end end def export_zip(opts = {}) mark_exporting begin - self.job_progress.try :start! + job_progress.try :start! if (attachment = Exporters::ZipExporter.create_zip_export(self, opts)) self.attachment = attachment self.progress = 100 @@ -245,7 +245,7 @@ def export_zip(opts = {}) add_error("Error running zip export.", $ERROR_INFO) mark_failed ensure - self.save + save end end @@ -255,15 +255,15 @@ def quizzes2_build_assignment(opts = {}) @quiz_exporter = Exporters::Quizzes2Exporter.new(self) if @quiz_exporter.export(opts) - self.update( + update( selected_content: { quizzes: { create_key(@quiz_exporter.quiz) => true } } ) - self.settings[:quizzes2] = @quiz_exporter.build_assignment_payload - self.save! + settings[:quizzes2] = @quiz_exporter.build_assignment_payload + save! return true else add_error("Error running export to Quizzes 2.", $ERROR_INFO) @@ -276,7 +276,7 @@ def quizzes2_build_assignment(opts = {}) def quizzes2_export_complete return unless quizzes_next? - assignment_id = self.settings.dig(:quizzes2, :assignment, :assignment_id) + assignment_id = settings.dig(:quizzes2, :assignment, :assignment_id) assignment = Assignment.find_by(id: assignment_id) if assignment.blank? mark_failed @@ -284,15 +284,15 @@ def quizzes2_export_complete end begin - self.update(export_type: QTI) + update(export_type: QTI) @cc_exporter = CC::CCExporter.new(self) if @cc_exporter.export - self.update( + update( export_type: QUIZZES2 ) - self.settings[:quizzes2][:qti_export] = {} - self.settings[:quizzes2][:qti_export][:url] = self.attachment.public_download_url + settings[:quizzes2][:qti_export] = {} + settings[:quizzes2][:qti_export][:url] = attachment.public_download_url self.progress = 100 mark_exported else @@ -304,7 +304,7 @@ def quizzes2_export_complete assignment.fail_to_migrate mark_failed ensure - self.save + save end end @@ -316,7 +316,7 @@ def export_quizzes2 @quiz_exporter = Exporters::Quizzes2Exporter.new(self) if @quiz_exporter.export - self.update( + update( export_type: QTI, selected_content: { quizzes: { @@ -324,16 +324,16 @@ def export_quizzes2 } } ) - self.settings[:quizzes2] = @quiz_exporter.build_assignment_payload + settings[:quizzes2] = @quiz_exporter.build_assignment_payload @cc_exporter = CC::CCExporter.new(self) end if @cc_exporter&.export - self.update( + update( export_type: QUIZZES2 ) - self.settings[:quizzes2][:qti_export] = {} - self.settings[:quizzes2][:qti_export][:url] = self.attachment.public_download_url + settings[:quizzes2][:qti_export] = {} + settings[:quizzes2][:qti_export][:url] = attachment.public_download_url self.progress = 100 mark_exported else @@ -343,20 +343,20 @@ def export_quizzes2 add_error("Error running export to Quizzes 2.", $ERROR_INFO) mark_failed ensure - self.save + save end end def queue_api_job(opts) - if self.job_progress - p = self.job_progress + if job_progress + p = job_progress else p = Progress.new(:context => self, :tag => "content_export") self.job_progress = p end p.workflow_state = 'queued' p.completion = 0 - p.user = self.user + p.user = user p.save! quizzes2_build_assignment(opts) if new_quizzes_page_enabled? export(opts) @@ -367,11 +367,11 @@ def referenced_files end def for_course_copy? - self.export_type == COURSE_COPY || self.export_type == MASTER_COURSE_COPY + export_type == COURSE_COPY || export_type == MASTER_COURSE_COPY end def for_master_migration? - self.export_type == MASTER_COURSE_COPY + export_type == MASTER_COURSE_COPY end def master_migration @@ -379,35 +379,35 @@ def master_migration end def common_cartridge? - self.export_type == COMMON_CARTRIDGE + export_type == COMMON_CARTRIDGE end def qti_export? - self.export_type == QTI + export_type == QTI end def quizzes2_export? - self.export_type == QUIZZES2 + export_type == QUIZZES2 end def zip_export? - self.export_type == ZIP + export_type == ZIP end def error_message - self.settings[:errors] ? self.settings[:errors].last : nil + settings[:errors] ? settings[:errors].last : nil end def error_messages - self.settings[:errors] ||= [] + settings[:errors] ||= [] end def selected_content=(copy_settings) - self.settings[:selected_content] = copy_settings + settings[:selected_content] = copy_settings end def selected_content - self.settings[:selected_content] ||= {} + settings[:selected_content] ||= {} end def select_content_key(obj) @@ -419,11 +419,11 @@ def select_content_key(obj) end def create_key(obj, prepend = "") - self.shard.activate do + shard.activate do if for_master_migration? && !is_external_object?(obj) master_migration.master_template.migration_id_for(obj, prepend) # because i'm too scared to use normal migration ids else - CC::CCHelper.create_key(obj, prepend, global: self.global_identifiers?) + CC::CCHelper.create_key(obj, prepend, global: global_identifiers?) end end end @@ -512,30 +512,30 @@ def add_exported_asset(obj) end def add_error(user_message, exception_or_info = nil) - self.settings[:errors] ||= [] + settings[:errors] ||= [] er = nil if exception_or_info.is_a?(Exception) out = Canvas::Errors.capture_exception(:course_export, exception_or_info) er = out[:error_report] - self.settings[:errors] << [user_message, "ErrorReport id: #{er}"] + settings[:errors] << [user_message, "ErrorReport id: #{er}"] else - self.settings[:errors] << [user_message, exception_or_info] + settings[:errors] << [user_message, exception_or_info] end - self.content_migration&.add_issue(user_message, :error, error_report_id: er) + content_migration&.add_issue(user_message, :error, error_report_id: er) end def root_account - self.context.try_rescue(:root_account) + context.try_rescue(:root_account) end def running? - ['created', 'exporting'].member? self.workflow_state + ['created', 'exporting'].member? workflow_state end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.attachment&.destroy_permanently_plus + attachment&.destroy_permanently_plus save! end @@ -547,10 +547,10 @@ def fast_update_progress(val) content_migration&.update_conversion_progress(val) self.progress = val ContentExport.where(:id => self).update_all(:progress => val) - if EpubExport.where(content_export_id: self.id).exists? - self.epub_export.update_progress_from_content_export!(val) + if EpubExport.where(content_export_id: id).exists? + epub_export.update_progress_from_content_export!(val) end - self.job_progress.try(:update_completion!, val) + job_progress.try(:update_completion!, val) end def self.expire_days @@ -564,8 +564,8 @@ def self.expire? def expired? return false unless ContentExport.expire? - if self.user - return false if self.user.content_shares.where(content_export: self).exists? + if user + return false if user.content_shares.where(content_export: self).exists? end created_at < ContentExport.expire_days.days.ago end diff --git a/app/models/content_migration.rb b/app/models/content_migration.rb index 53a0c6fb8b5b8..be4a689716c4a 100644 --- a/app/models/content_migration.rb +++ b/app/models/content_migration.rb @@ -68,7 +68,7 @@ def self.migration_plugins(exclude_hidden = false) set_policy do given do |user, session| - self.context.grants_any_right?(user, session, *RoleOverride::GRANULAR_FILE_PERMISSIONS) + context.grants_any_right?(user, session, *RoleOverride::GRANULAR_FILE_PERMISSIONS) end can :read end @@ -76,7 +76,7 @@ def self.migration_plugins(exclude_hidden = false) def trigger_live_events! # Trigger live events for the source course and migration Canvas::LiveEventsCallbacks.after_update(context, context.saved_changes) - Canvas::LiveEventsCallbacks.after_update(self, self.saved_changes) + Canvas::LiveEventsCallbacks.after_update(self, saved_changes) # Trigger live events for all updated/created records imported_migration_items.each do |imported_item| @@ -103,7 +103,7 @@ def set_started_at_and_finished_at end def quota_context - self.context + context end def migration_settings @@ -112,7 +112,7 @@ def migration_settings # this is needed by Attachment#clone_for, which is used to allow a ContentExport to be directly imported def attachments - Attachment.where(id: self.attachment_id) + Attachment.where(id: attachment_id) end def update_migration_settings(new_settings) @@ -126,7 +126,7 @@ def import_immediately? end def content_export - if self.persisted? && !association(:content_export).loaded? && source_course_id && Shard.shard_for(source_course_id) != self.shard + if persisted? && !association(:content_export).loaded? && source_course_id && Shard.shard_for(source_course_id) != shard association(:content_export).target = Shard.shard_for(source_course_id).activate { ContentExport.where(:content_migration_id => self).first } end super @@ -157,8 +157,8 @@ def initiated_source=(value) end def n_strand - account_identifier = self.root_account.try(:global_id) || "global" - type = self.for_master_course_import? ? "master_course" : self.initiated_source + account_identifier = root_account.try(:global_id) || "global" + type = for_master_course_import? ? "master_course" : initiated_source ["migrations:import_content", "#{type}_#{account_identifier}"] end @@ -212,7 +212,7 @@ def skip_job_progress def root_account return super if root_account_id - self.context.root_account rescue nil + context.root_account rescue nil end def migration_type @@ -249,7 +249,7 @@ def canvas_import? }.freeze def add_issue(user_message, type, opts = {}) - mi = self.migration_issues.build(:issue_type => type.to_s, :description => user_message) + mi = migration_issues.build(:issue_type => type.to_s, :description => user_message) if opts[:error_report_id] mi.error_report_id = opts[:error_report_id] elsif opts[:exception] @@ -261,9 +261,9 @@ def add_issue(user_message, type, opts = {}) mi.fix_issue_html_url = opts[:fix_issue_html_url] # prevent duplicates - if self.migration_issues.where(mi.attributes.slice( - "issue_type", "description", "error_message", "fix_issue_html_url" - )).any? + if migration_issues.where(mi.attributes.slice( + "issue_type", "description", "error_message", "fix_issue_html_url" + )).any? mi.delete else mi.save! @@ -321,13 +321,13 @@ def fail_with_error!(exception_or_info, error_message: nil, issue_level: :error) self.workflow_state = :failed job_progress.fail if job_progress && !skip_job_progress save - self.update_master_migration('failed') if for_master_course_import? + update_master_migration('failed') if for_master_course_import? resolve_content_links! # don't leave placeholders end # deprecated warning format def old_warnings_format - self.migration_issues.map do |mi| + migration_issues.map do |mi| message = mi.error_report_id ? "ErrorReport:#{mi.error_report_id}" : mi.error_message [mi.description, message] end @@ -341,13 +341,13 @@ def warnings def file_upload_success_callback(att) if att.file_state == "available" self.attachment = att - self.migration_issues.delete_all if self.migration_issues.any? + migration_issues.delete_all if migration_issues.any? self.workflow_state = :pre_processed - self.save - self.queue_migration + save + queue_migration else self.workflow_state = :pre_process_error - self.add_warning(t('bad_attachment', "The file was not successfully uploaded.")) + add_warning(t('bad_attachment', "The file was not successfully uploaded.")) end end @@ -355,15 +355,15 @@ def reset_job_progress(wf_state = :queued) return if skip_job_progress self.progress = 0 - if self.job_progress - p = self.job_progress + if job_progress + p = job_progress else - p = self.shard.activate { Progress.new(:context => self, :tag => "content_migration") } + p = shard.activate { Progress.new(:context => self, :tag => "content_migration") } self.job_progress = p end p.workflow_state = wf_state p.completion = 0 - p.user = self.user + p.user = user p.save! p end @@ -380,25 +380,25 @@ def queue_migration(plugin = nil, retry_count: 0, expires_at: nil) if plugin queue_opts = { :priority => Delayed::LOW_PRIORITY, :max_attempts => 1, :expires_at => expires_at } - if self.strand - queue_opts[:strand] = self.strand + if strand + queue_opts[:strand] = strand else - queue_opts[:n_strand] = self.n_strand + queue_opts[:n_strand] = n_strand end - if plugin.settings[:import_immediately] || (self.workflow_state == 'exported' && !plugin.settings[:skip_conversion_step]) + if plugin.settings[:import_immediately] || (workflow_state == 'exported' && !plugin.settings[:skip_conversion_step]) # it's ready to be imported self.workflow_state = :importing - self.save + save delay(**queue_opts.merge(on_permanent_failure: :fail_with_error!)).import_content else # find worker and queue for conversion begin worker_class = Canvas::Migration::Worker.const_get(plugin.settings['worker']) self.workflow_state = :exporting - self.save + save self.class.connection.after_transaction_commit do - Delayed::Job.enqueue(worker_class.new(self.id), queue_opts) + Delayed::Job.enqueue(worker_class.new(id), queue_opts) end rescue NameError self.workflow_state = 'failed' @@ -406,7 +406,7 @@ def queue_migration(plugin = nil, retry_count: 0, expires_at: nil) migration_settings[:last_error] = message Canvas::Errors.capture_exception(:content_migration, $ERROR_INFO) logger.error message - self.save + save end end else @@ -414,27 +414,27 @@ def queue_migration(plugin = nil, retry_count: 0, expires_at: nil) message = "No migration plugin of type #{migration_type} found." migration_settings[:last_error] = message logger.error message - self.save + save end end alias_method :export_content, :queue_migration def blocked_by_current_migration?(plugin, retry_count, expires_at) - return false if self.migration_type == "zip_file_importer" + return false if migration_type == "zip_file_importer" running_cutoff = Setting.get('content_migration_job_block_hours', '4').to_i.hours.ago # at some point just let the jobs keep going - if self.context && self.context.content_migrations - .where(:workflow_state => %w[created queued pre_processing pre_processed exporting importing]).where("id < ?", self.id) - .where("started_at > ?", running_cutoff).exists? + if context && context.content_migrations + .where(:workflow_state => %w[created queued pre_processing pre_processed exporting importing]).where("id < ?", id) + .where("started_at > ?", running_cutoff).exists? # there's another job already going so punt if retry_count > 5 - self.fail_with_error!(I18n.t("Blocked by running migration")) + fail_with_error!(I18n.t("Blocked by running migration")) else self.workflow_state = :queued - self.save + save run_at = Setting.get('content_migration_requeue_delay_minutes', '60').to_i.minutes.from_now # if everything goes right, we'll queue it right away after the currently running one finishes @@ -443,9 +443,9 @@ def blocked_by_current_migration?(plugin, retry_count, expires_at) plugin, retry_count: retry_count + 1, expires_at: expires_at ) - if self.job_progress - self.job_progress.delayed_job_id = job.id - self.job_progress.save! + if job_progress + job_progress.delayed_job_id = job.id + job_progress.save! end end @@ -456,16 +456,16 @@ def blocked_by_current_migration?(plugin, retry_count, expires_at) end def set_default_settings - if self.context.respond_to?(:root_account) && - (account = self.context.root_account) && + if context.respond_to?(:root_account) && + (account = context.root_account) && (default_ms = account.settings[:default_migration_settings]) - self.migration_settings = default_ms.merge(self.migration_settings).with_indifferent_access + self.migration_settings = default_ms.merge(migration_settings).with_indifferent_access end - unless self.migration_settings.key?(:overwrite_quizzes) - self.migration_settings[:overwrite_quizzes] = for_course_copy? || for_master_course_import? || (self.migration_type && self.migration_type == 'canvas_cartridge_importer') + unless migration_settings.key?(:overwrite_quizzes) + migration_settings[:overwrite_quizzes] = for_course_copy? || for_master_course_import? || (migration_type && migration_type == 'canvas_cartridge_importer') end - self.migration_settings.reverse_merge!(:prefer_existing_tools => true) if self.migration_type == 'common_cartridge_importer' # default to true + migration_settings.reverse_merge!(:prefer_existing_tools => true) if migration_type == 'common_cartridge_importer' # default to true check_quiz_id_prepender end @@ -473,7 +473,7 @@ def set_default_settings def process_domain_substitutions(url) unless @domain_substitution_map @domain_substitution_map = {} - (self.migration_settings[:domain_substitution_map] || {}).each do |k, v| + (migration_settings[:domain_substitution_map] || {}).each do |k, v| @domain_substitution_map[k.to_s] = v.to_s # ensure strings end end @@ -488,10 +488,10 @@ def process_domain_substitutions(url) end def check_quiz_id_prepender - return unless self.context.respond_to?(:assessment_questions) + return unless context.respond_to?(:assessment_questions) if !migration_settings[:id_prepender] && (!migration_settings[:overwrite_questions] || !migration_settings[:overwrite_quizzes]) - migration_settings[:id_prepender] = self.id + migration_settings[:id_prepender] = id end end @@ -545,10 +545,10 @@ def capture_job_id job = Delayed::Worker.current_job return false unless job - self.migration_settings[:job_ids] ||= [] - return false if self.migration_settings[:job_ids].include?(job.id) + migration_settings[:job_ids] ||= [] + return false if migration_settings[:job_ids].include?(job.id) - self.migration_settings[:job_ids] << job.id + migration_settings[:job_ids] << job.id true end @@ -556,18 +556,18 @@ def import_content reset_job_progress(:running) unless import_immediately? self.workflow_state = :importing capture_job_id - self.save + save - Lti::Asset.opaque_identifier_for(self.context) + Lti::Asset.opaque_identifier_for(context) all_files_path = nil begin data = nil - if self.for_master_course_import? - self.master_course_subscription.load_tags! # load child content tags - self.master_course_subscription.master_template.preload_restrictions! + if for_master_course_import? + master_course_subscription.load_tags! # load child content tags + master_course_subscription.master_template.preload_restrictions! - data = JSON.parse(self.exported_attachment.open, :max_nesting => 50) + data = JSON.parse(exported_attachment.open, :max_nesting => 50) data = prepare_data(data) # handle deletions before files are copied @@ -575,22 +575,22 @@ def import_content process_master_deletions(deletions.except('AssignmentGroup')) if deletions # wait until after the import to do AssignmentGroups # copy the attachments - source_export = ContentExport.find(self.migration_settings[:master_course_export_id]) + source_export = ContentExport.find(migration_settings[:master_course_export_id]) if source_export.selective_export? # load in existing attachments to path resolution map file_mig_ids = source_export.settings[:referenced_file_migration_ids] if file_mig_ids.present? # ripped from copy_attachments_from_course - root_folder_name = Folder.root_folders(self.context).first.name + '/' - self.context.attachments.where(:migration_id => file_mig_ids).each do |file| - self.add_attachment_path(file.full_display_path.gsub(/\A#{root_folder_name}/, ''), file.migration_id) + root_folder_name = Folder.root_folders(context).first.name + '/' + context.attachments.where(:migration_id => file_mig_ids).each do |file| + add_attachment_path(file.full_display_path.gsub(/\A#{root_folder_name}/, ''), file.migration_id) end end end # sync the existing folders first in case someone did something weird like deleted and replaced a folder in the same sync - MasterCourses::FolderHelper.update_folder_names_and_states(self.context, source_export) - self.context.copy_attachments_from_course(source_export.context, :content_export => source_export, :content_migration => self) - MasterCourses::FolderHelper.recalculate_locked_folders(self.context) + MasterCourses::FolderHelper.update_folder_names_and_states(context, source_export) + context.copy_attachments_from_course(source_export.context, :content_export => source_export, :content_migration => self) + MasterCourses::FolderHelper.recalculate_locked_folders(context) else @exported_data_zip = download_exported_data @zip_file = Zip::File.open(@exported_data_zip.path) @@ -615,19 +615,19 @@ def import_content process_master_deletions(deletions.slice('AssignmentGroup')) if deletions - unless self.import_immediately? + unless import_immediately? update_import_progress(100) end - if self.for_master_course_import? - self.update_master_migration('completed') + if for_master_course_import? + update_master_migration('completed') end rescue => e self.workflow_state = :failed er_id = Canvas::Errors.capture_exception(:content_migration, e)[:error_report] migration_settings[:last_error] = "ErrorReport:#{er_id}" logger.error e - self.save - self.update_master_migration('failed') if self.for_master_course_import? + save + update_master_migration('failed') if for_master_course_import? raise e ensure File.delete(all_files_path) if all_files_path && File.exist?(all_files_path) @@ -639,11 +639,11 @@ def import_content def import!(data) return import_quizzes_next!(data) if quizzes_next_migration? - Importers.content_importer_for(self.context_type) + Importers.content_importer_for(context_type) .import_content( - self.context, + context, data, - self.migration_settings[:migration_ids_to_import], + migration_settings[:migration_ids_to_import], self ) end @@ -655,19 +655,19 @@ def quizzes_next_migration? end def quizzes_next_banks_migration? - self.quizzes_next_migration? && Account.site_admin.feature_enabled?(:new_quizzes_bank_migrations) + quizzes_next_migration? && Account.site_admin.feature_enabled?(:new_quizzes_bank_migrations) end def import_quizzes_next!(data) quizzes2_importer = QuizzesNext::Importers::CourseContentImporter.new(data, self) quizzes2_importer.import_content( - self.migration_settings[:migration_ids_to_import] + migration_settings[:migration_ids_to_import] ) end def master_migration - @master_migration ||= self.shard.activate { MasterCourses::MasterMigration.find(self.migration_settings[:master_migration_id]) } + @master_migration ||= shard.activate { MasterCourses::MasterMigration.find(migration_settings[:master_migration_id]) } end def update_master_migration(state) @@ -675,9 +675,9 @@ def update_master_migration(state) end def master_course_subscription - return unless self.for_master_course_import? + return unless for_master_course_import? - @master_course_subscription ||= self.shard.activate { MasterCourses::ChildSubscription.find(self.child_subscription_id) } + @master_course_subscription ||= shard.activate { MasterCourses::ChildSubscription.find(child_subscription_id) } end def prepare_data(data) @@ -688,20 +688,20 @@ def prepare_data(data) end def copy_options - self.migration_settings[:copy_options] + migration_settings[:copy_options] end def copy_options=(options) - self.migration_settings[:copy_options] = options + migration_settings[:copy_options] = options set_date_shift_options options end def for_course_copy? - self.migration_type == 'course_copy_importer' || for_master_course_import? + migration_type == 'course_copy_importer' || for_master_course_import? end def for_master_course_import? - self.migration_type == 'master_course_import' + migration_type == 'master_course_import' end def add_skipped_item(item) @@ -717,9 +717,9 @@ def process_master_deletions(deletions) mig_ids = deletions[klass] item_scope = case klass when 'Attachment' - self.context.attachments.not_deleted.where(migration_id: mig_ids) + context.attachments.not_deleted.where(migration_id: mig_ids) else - klass.constantize.where(context_id: self.context, context_type: 'Course', migration_id: mig_ids) + klass.constantize.where(context_id: context, context_type: 'Course', migration_id: mig_ids) .where.not(workflow_state: 'deleted') end item_scope.each do |content| @@ -742,13 +742,13 @@ def process_master_deletions(deletions) end def check_cross_institution - return unless self.context.is_a?(Course) + return unless context.is_a?(Course) - data = self.context.full_migration_hash + data = context.full_migration_hash return unless data source_root_account_uuid = data[:course] && data[:course][:root_account_uuid] - @cross_institution = source_root_account_uuid && source_root_account_uuid != self.context.root_account.uuid + @cross_institution = source_root_account_uuid && source_root_account_uuid != context.root_account.uuid end def cross_institution? @@ -757,12 +757,12 @@ def cross_institution? def set_date_shift_options(opts) if opts && (Canvas::Plugin.value_to_boolean(opts[:shift_dates]) || Canvas::Plugin.value_to_boolean(opts[:remove_dates])) - self.migration_settings[:date_shift_options] = opts.slice(:shift_dates, :remove_dates, :old_start_date, :old_end_date, :new_start_date, :new_end_date, :day_substitutions, :time_zone) + migration_settings[:date_shift_options] = opts.slice(:shift_dates, :remove_dates, :old_start_date, :old_end_date, :new_start_date, :new_end_date, :day_substitutions, :time_zone) end end def date_shift_options - self.migration_settings[:date_shift_options] + migration_settings[:date_shift_options] end def valid_date_shift_options @@ -783,10 +783,10 @@ def complete? end def download_exported_data - raise "No exported data to import" unless self.exported_attachment + raise "No exported data to import" unless exported_attachment config = ConfigFile.load('external_migration') || {} - @exported_data_zip = self.exported_attachment.open( + @exported_data_zip = exported_attachment.open( :need_local_file => true, :temp_folder => config[:data_folder] ) @@ -825,17 +825,17 @@ def update_import_progress(prog) end def progress - return nil if self.workflow_state == 'created' + return nil if workflow_state == 'created' mig_prog = read_attribute(:progress) || 0 - if self.for_course_copy? + if for_course_copy? # this is for a course copy so it needs to combine the progress of the export and import # The export will count for 40% of progress # The importing step (so the value of progress on this object)will be 60% mig_prog *= 0.6 - if self.content_export - export_prog = self.content_export.progress || 0 + if content_export + export_prog = content_export.progress || 0 mig_prog += export_prog * 0.4 end end @@ -882,11 +882,11 @@ def add_warning_for_missing_content_links(type, field, missing_links, fix_issue_ UPLOAD_TIMEOUT = 1.hour def check_for_pre_processing_timeout - if self.pre_processing? && (self.updated_at.utc + UPLOAD_TIMEOUT) < Time.now.utc + if pre_processing? && (updated_at.utc + UPLOAD_TIMEOUT) < Time.now.utc add_error(t(:upload_timeout_error, "The file upload process timed out.")) self.workflow_state = :failed job_progress.fail if job_progress && !skip_job_progress - self.save + save end end @@ -920,10 +920,10 @@ def self.collection_name(key) end def use_global_identifiers? - if self.content_export - self.content_export.global_identifiers? - elsif self.source_course - self.source_course.content_exports.temp_record.can_use_global_identifiers? + if content_export + content_export.global_identifiers? + elsif source_course + source_course.content_exports.temp_record.can_use_global_identifiers? else false end @@ -1048,8 +1048,8 @@ def handle_import_in_progress_notice end def check_for_blocked_migration - if self.saved_change_to_workflow_state? && %w[pre_process_error exported imported failed].include?(workflow_state) - if self.context && (next_cm = self.context.content_migrations.where(:workflow_state => 'queued').order(:id).first) + if saved_change_to_workflow_state? && %w[pre_process_error exported imported failed].include?(workflow_state) + if context && (next_cm = context.content_migrations.where(:workflow_state => 'queued').order(:id).first) job_id = next_cm.job_progress.try(:delayed_job_id) if job_id && (job = Delayed::Job.where(:id => job_id, :locked_at => nil).first) job.run_at = Time.now # it's okay to try it again now @@ -1061,11 +1061,11 @@ def check_for_blocked_migration def set_root_account_id self.root_account_id ||= - case self.context + case context when Course, Group - self.context.root_account_id + context.root_account_id when Account - self.context.resolved_root_account_id + context.resolved_root_account_id when User 0 # root account id unknown, use dummy root account id end @@ -1073,7 +1073,7 @@ def set_root_account_id end def notification_link_anchor - "!/blueprint/blueprint_subscriptions/#{self.child_subscription_id}/#{id}" + "!/blueprint/blueprint_subscriptions/#{child_subscription_id}/#{id}" end set_broadcast_policy do |p| diff --git a/app/models/content_participation.rb b/app/models/content_participation.rb index 89c614c9288a6..799458bedd8da 100644 --- a/app/models/content_participation.rb +++ b/app/models/content_participation.rb @@ -64,6 +64,6 @@ def update_participation_count end def set_root_account_id - self.root_account_id = self.content.assignment.root_account_id + self.root_account_id = content.assignment.root_account_id end end diff --git a/app/models/content_participation_count.rb b/app/models/content_participation_count.rb index 543bf808d66d0..51e6408d88875 100644 --- a/app/models/content_participation_count.rb +++ b/app/models/content_participation_count.rb @@ -61,7 +61,7 @@ def self.unread_count_for(type, context, user) case type when "Submission" - self.unread_submission_count_for(context, user) + unread_submission_count_for(context, user) else 0 end @@ -112,17 +112,17 @@ def self.unread_submission_count_for(context, user) end def unread_count(refresh: true) - refresh_unread_count if refresh && !frozen? && ttl.present? && self.updated_at.utc < ttl.seconds.ago.utc + refresh_unread_count if refresh && !frozen? && ttl.present? && updated_at.utc < ttl.seconds.ago.utc read_attribute(:unread_count) end def refresh_unread_count self.unread_count = ContentParticipationCount.unread_count_for(content_type, context, user) - GuardRail.activate(:primary) { self.save } if self.changed? + GuardRail.activate(:primary) { save } if changed? end def set_root_account_id - self.root_account_id = self.context&.root_account_id + self.root_account_id = context&.root_account_id end # Things we know of that will only get updated by a refresh: diff --git a/app/models/content_share.rb b/app/models/content_share.rb index dd7922f8a828b..31b737ee22299 100644 --- a/app/models/content_share.rb +++ b/app/models/content_share.rb @@ -47,13 +47,13 @@ class ContentShare < ActiveRecord::Base scope :by_date, -> { order(created_at: :desc) } def clone_for(receiver) - receiver.received_content_shares.create!(sender: self.user, - content_export: self.content_export, - name: self.name, + receiver.received_content_shares.create!(sender: user, + content_export: content_export, + name: name, read_state: 'unread') end def set_root_account_id - self.root_account_id = self.content_export&.context&.root_account_id if self.content_export&.context.respond_to?(:root_account_id) + self.root_account_id = content_export&.context&.root_account_id if content_export&.context.respond_to?(:root_account_id) end end diff --git a/app/models/content_tag.rb b/app/models/content_tag.rb index 4a37fbed93920..ad4ba40c19f34 100644 --- a/app/models/content_tag.rb +++ b/app/models/content_tag.rb @@ -74,7 +74,7 @@ class LastLinkToOutcomeNotDestroyed < StandardError acts_as_list :scope => :context_module set_policy do - given { |user, session| self.context&.grants_right?(user, session, :manage_content) } + given { |user, session| context&.grants_right?(user, session, :manage_content) } can :delete end @@ -96,9 +96,9 @@ class LastLinkToOutcomeNotDestroyed < StandardError attr_accessor :skip_touch def touch_context_module - return true if skip_touch.present? || self.context_module_id.nil? + return true if skip_touch.present? || context_module_id.nil? - ContentTag.touch_context_modules([self.context_module_id]) + ContentTag.touch_context_modules([context_module_id]) end def touch_context_module_after_transaction @@ -120,16 +120,16 @@ def self.touch_context_modules(ids = []) end def touch_context_if_learning_outcome - if (self.tag_type == 'learning_outcome_association' || self.tag_type == 'learning_outcome') && skip_touch.blank? - self.context_type.constantize.where(:id => self.context_id).update_all(:updated_at => Time.now.utc) + if (tag_type == 'learning_outcome_association' || tag_type == 'learning_outcome') && skip_touch.blank? + context_type.constantize.where(:id => context_id).update_all(:updated_at => Time.now.utc) end end def update_outcome_contexts - return unless self.tag_type == 'learning_outcome_association' + return unless tag_type == 'learning_outcome_association' - if self.context_type == 'Account' || self.context_type == 'Course' - self.content.add_root_account_id_for_context!(self.context) + if context_type == 'Account' || context_type == 'Course' + content.add_root_account_id_for_context!(context) end end @@ -141,22 +141,22 @@ def associate_external_tool end def default_values - self.title ||= self.content.title rescue nil - self.title ||= self.content.name rescue nil - self.title ||= self.content.display_name rescue nil + self.title ||= content.title rescue nil + self.title ||= content.name rescue nil + self.title ||= content.display_name rescue nil self.title ||= t(:no_title, "No title") self.comments ||= "" self.comments = "" if self.comments == "Comments" - self.context_code = "#{self.context_type.to_s.underscore}_#{self.context_id}" + self.context_code = "#{context_type.to_s.underscore}_#{context_id}" end protected :default_values def context_code - read_attribute(:context_code) || "#{self.context_type.to_s.underscore}_#{self.context_id}" rescue nil + read_attribute(:context_code) || "#{context_type.to_s.underscore}_#{context_id}" rescue nil end def context_name - self.context.name rescue "" + context.name rescue "" end def update_could_be_locked @@ -181,23 +181,23 @@ def self.update_could_be_locked(tags = []) end def confirm_valid_module_requirements - self.context_module&.confirm_valid_requirements + context_module&.confirm_valid_requirements end def scoreable? - self.content_type_quiz? || self.graded? + content_type_quiz? || graded? end def graded? - return true if self.content_type == 'Assignment' - return false if self.content_type == 'WikiPage' - return false unless self.can_have_assignment? + return true if content_type == 'Assignment' + return false if content_type == 'WikiPage' + return false unless can_have_assignment? content && !content.assignment_id.nil? end def duplicate_able? - case self.content_type_class + case content_type_class when 'assignment' content&.can_duplicate? when 'discussion_topic', 'wiki_page' @@ -220,11 +220,11 @@ def direct_share_select_class end def content_type_class(is_student = false) - case self.content_type + case content_type when 'Assignment' - if self.content && self.content.submission_types == 'online_quiz' + if content && content.submission_types == 'online_quiz' is_student ? 'lti-quiz' : 'quiz' - elsif self.content && self.content.submission_types == 'discussion_topic' + elsif content && content.submission_types == 'discussion_topic' 'discussion_topic' elsif self&.content&.quiz_lti? 'lti-quiz' @@ -234,25 +234,25 @@ def content_type_class(is_student = false) when 'Quizzes::Quiz' is_student ? 'lti-quiz' : 'quiz' else - self.content_type.underscore + content_type.underscore end rescue - (self.content_type || "").underscore + (content_type || "").underscore end def item_class - (self.content_type || "").gsub(/\A[A-Za-z]+::/, '') + '_' + self.content_id.to_s + (content_type || "").gsub(/\A[A-Za-z]+::/, '') + '_' + content_id.to_s end def can_have_assignment? - ['Assignment', 'DiscussionTopic', 'Quizzes::Quiz', 'WikiPage'].include?(self.content_type) + ['Assignment', 'DiscussionTopic', 'Quizzes::Quiz', 'WikiPage'].include?(content_type) end def assignment - if self.content_type == 'Assignment' - self.content + if content_type == 'Assignment' + content elsif can_have_assignment? - self.content&.assignment + content&.assignment else nil end @@ -260,7 +260,7 @@ def assignment alias_method :old_content, :content def content - TABLELESS_CONTENT_TYPES.include?(self.content_type) ? nil : old_content + TABLELESS_CONTENT_TYPES.include?(content_type) ? nil : old_content end def content_or_self @@ -269,7 +269,7 @@ def content_or_self def asset_safe_title(column) name = self.title.to_s - if (limit = self.content.class.try(:columns_hash)[column].try(:limit)) && name.length > limit + if (limit = content.class.try(:columns_hash)[column].try(:limit)) && name.length > limit name = name[0, limit][/.{0,#{limit}}/mu] end name @@ -299,16 +299,16 @@ def self.asset_workflow_state(asset) end def asset_workflow_state - ContentTag.asset_workflow_state(self.content) + ContentTag.asset_workflow_state(content) end def asset_context_matches? - self.content.respond_to?(:context) && self.content.context == context + content.respond_to?(:context) && content.context == context end def update_asset_name!(user = nil) - return unless self.sync_title_to_asset_title? - return unless self.asset_context_matches? + return unless sync_title_to_asset_title? + return unless asset_context_matches? # Assignment proxies name= and name to title= and title, which breaks the asset_safe_title logic if content.respond_to?("name=") && content.respond_to?("name") && !content.is_a?(Assignment) @@ -325,17 +325,17 @@ def update_asset_name!(user = nil) end def update_asset_workflow_state! - return unless self.sync_workflow_state_to_asset? - return unless self.asset_context_matches? - return unless self.content.respond_to?(:publish!) + return unless sync_workflow_state_to_asset? + return unless asset_context_matches? + return unless content.respond_to?(:publish!) # update the asset and also update _other_ content tags that point at it - if self.unpublished? && self.content.published? && self.content.can_unpublish? - self.content.unpublish! - self.class.update_for(self.content, exclude_tag: self) - elsif self.active? && !self.content.published? - self.content.publish! - self.class.update_for(self.content, exclude_tag: self) + if unpublished? && content.published? && content.can_unpublish? + content.unpublish! + self.class.update_for(content, exclude_tag: self) + elsif active? && !content.published? + content.publish! + self.class.update_for(content, exclude_tag: self) end end @@ -346,22 +346,22 @@ def self.delete_for(asset) def can_destroy? # if it's a learning outcome link... - if self.tag_type == 'learning_outcome_association' + if tag_type == 'learning_outcome_association' # and there are no other links to the same outcome in the same context... - outcome = self.content + outcome = content other_link = ContentTag.learning_outcome_links.active - .where(:context_type => self.context_type, :context_id => self.context_id, :content_id => outcome) + .where(:context_type => context_type, :context_id => context_id, :content_id => outcome) .where("id<>?", self).first unless other_link # and there are alignments to the outcome (in the link's context for # foreign links, in any context for native links) alignment_conditions = { :learning_outcome_id => outcome.id } - native = outcome.context_type == self.context_type && outcome.context_id == self.context_id + native = outcome.context_type == context_type && outcome.context_id == context_id if native @should_destroy_outcome = true else - alignment_conditions[:context_id] = self.context_id - alignment_conditions[:context_type] = self.context_type + alignment_conditions[:context_id] = context_id + alignment_conditions[:context_type] = context_type end @active_alignment_tags = ContentTag.learning_outcome_alignments.active.where(alignment_conditions) @@ -384,10 +384,10 @@ def destroy context_module&.remove_completion_requirement(id) self.workflow_state = 'deleted' - self.save! + save! # for outcome links delete the associated friendly description - delete_outcome_friendly_description if self.content_type == 'LearningOutcome' + delete_outcome_friendly_description if content_type == 'LearningOutcome' run_due_date_cacher_for_quizzes_next(force: true) @@ -396,40 +396,40 @@ def destroy # (a) LearningOutcome#destroy *should* only ever be called from here, and # (b) we've already determined other_link and native if @should_destroy_outcome - self.content.destroy + content.destroy end true end def locked_for?(user, opts = {}) - return unless self.context_module && !self.context_module.deleted? + return unless context_module && !context_module.deleted? - self.context_module.locked_for?(user, opts.merge({ :tag => self })) + context_module.locked_for?(user, opts.merge({ :tag => self })) end def available_for?(user, opts = {}) - self.context_module.available_for?(user, opts.merge({ :tag => self })) + context_module.available_for?(user, opts.merge({ :tag => self })) end def send_items_to_stream - if self.content_type == "DiscussionTopic" && self.saved_change_to_workflow_state? && self.workflow_state == 'active' + if content_type == "DiscussionTopic" && saved_change_to_workflow_state? && workflow_state == 'active' content.send_items_to_stream end end def clear_discussion_stream_items - if self.content_type == "DiscussionTopic" - if self.saved_change_to_workflow_state? && - ['active', nil].include?(self.workflow_state_before_last_save) && - self.workflow_state == 'unpublished' + if content_type == "DiscussionTopic" + if saved_change_to_workflow_state? && + ['active', nil].include?(workflow_state_before_last_save) && + workflow_state == 'unpublished' content.clear_stream_items end end end def clear_stream_items_if_module_is_unpublished - if self.content_type == "DiscussionTopic" && context_module&.workflow_state == 'unpublished' + if content_type == "DiscussionTopic" && context_module&.workflow_state == 'unpublished' content.clear_stream_items end end @@ -463,24 +463,24 @@ def self.update_for(asset, exclude_tag: nil) end def sync_title_to_asset_title? - self.tag_type != "learning_outcome_association" && !['ContextExternalTool', 'Attachment'].member?(self.content_type) + tag_type != "learning_outcome_association" && !['ContextExternalTool', 'Attachment'].member?(content_type) end def sync_workflow_state_to_asset? - self.content_type_quiz? || ['Attachment', 'Assignment', 'WikiPage', 'DiscussionTopic'].include?(self.content_type) + content_type_quiz? || ['Attachment', 'Assignment', 'WikiPage', 'DiscussionTopic'].include?(content_type) end def content_type_quiz? - Quizzes::Quiz.class_names.include?(self.content_type) + Quizzes::Quiz.class_names.include?(content_type) end def content_type_discussion? - 'DiscussionTopic' == self.content_type + 'DiscussionTopic' == content_type end def context_module_action(user, action, points = nil) GuardRail.activate(:primary) do - self.context_module&.update_for(user, action, self, points) + context_module&.update_for(user, action, self, points) end end @@ -489,11 +489,11 @@ def progression_for_user(user) end def content_asset_string - @content_asset_string ||= "#{self.content_type.underscore}_#{self.content_id}" + @content_asset_string ||= "#{content_type.underscore}_#{content_id}" end def associated_asset_string - @associated_asset_string ||= "#{self.associated_asset_type.underscore}_#{self.associated_asset_id}" + @associated_asset_string ||= "#{associated_asset_type.underscore}_#{associated_asset_id}" end def content_asset_string=(val) @@ -632,18 +632,18 @@ def self.order_by_outcome_title end def visible_to_user?(user, opts = nil, session = nil) - return unless self.context_module + return unless context_module - opts ||= self.context_module.visibility_for_user(user, session) + opts ||= context_module.visibility_for_user(user, session) return false unless opts[:can_read] return true if opts[:can_read_as_admin] - return false unless self.published? + return false unless published? - if self.assignment - self.assignment.visible_to_user?(user, opts) - elsif self.content_type_quiz? - self.content.visible_to_user?(user, opts) + if assignment + assignment.visible_to_user?(user, opts) + elsif content_type_quiz? + content.visible_to_user?(user, opts) else true end @@ -654,9 +654,9 @@ def mark_as_importing!(migration) end def check_for_restricted_content_changes - if !self.new_record? && self.title_changed? && !@importing_migration && self.content && self.content.respond_to?(:is_child_content?) && - self.content.is_child_content? && self.content.editing_restricted?(:content) - self.errors.add(:title, "cannot change title - associated content locked by Master Course") + if !new_record? && title_changed? && !@importing_migration && content && content.respond_to?(:is_child_content?) && + content.is_child_content? && content.editing_restricted?(:content) + errors.add(:title, "cannot change title - associated content locked by Master Course") end end @@ -669,13 +669,13 @@ def run_due_date_cacher_for_quizzes_next(force: false) end def set_root_account - return if self.root_account_id.present? + return if root_account_id.present? - self.root_account_id = case self.context + self.root_account_id = case context when Account - self.context.resolved_root_account_id + context.resolved_root_account_id else - self.context&.root_account_id + context&.root_account_id end end @@ -699,6 +699,6 @@ def clear_total_outcomes_cache end def delete_outcome_friendly_description - OutcomeFriendlyDescription.active.find_by(context: self.context, learning_outcome_id: self.content_id)&.destroy + OutcomeFriendlyDescription.active.find_by(context: context, learning_outcome_id: content_id)&.destroy end end diff --git a/app/models/context.rb b/app/models/context.rb index 2e8e66ce7c82b..04e747376190e 100644 --- a/app/models/context.rb +++ b/app/models/context.rb @@ -57,7 +57,7 @@ module Context def clear_cached_short_name self.class.connection.after_transaction_commit do - Rails.cache.delete(['short_name_lookup', self.asset_string].cache_key) + Rails.cache.delete(['short_name_lookup', asset_string].cache_key) end end @@ -71,7 +71,7 @@ def add_aggregate_entries(entries, feed) :message => entry.message ) elsif !entry.asset - announcement = self.announcements.build( + announcement = announcements.build( :title => entry.title, :message => entry.message ) @@ -90,11 +90,11 @@ def self.sorted_rubrics(context) def rubric_contexts(user) associations = [] - course_ids = [self.id] + course_ids = [id] course_ids = (course_ids + user.participating_instructor_course_with_concluded_ids.map { |id| Shard.relative_id_for(id, user.shard, Shard.current) }).uniq if user Shard.partition_by_shard(course_ids) do |sharded_course_ids| context_codes = sharded_course_ids.map { |id| "course_#{id}" } - if Shard.current == self.shard + if Shard.current == shard context = self while context.respond_to?(:account) || context.respond_to?(:parent_account) context = context.respond_to?(:account) ? context.account : context.parent_account @@ -121,18 +121,18 @@ def active_record_types(only_check: nil) return @active_record_types[only_check] if @active_record_types[only_check] possible_types = { - files: -> { self.respond_to?(:attachments) && self.attachments.active.exists? }, - modules: -> { self.respond_to?(:context_modules) && self.context_modules.active.exists? }, + files: -> { respond_to?(:attachments) && attachments.active.exists? }, + modules: -> { respond_to?(:context_modules) && context_modules.active.exists? }, quizzes: -> { - (self.respond_to?(:quizzes) && self.quizzes.active.exists?) || - (self.respond_to?(:assignments) && self.assignments.active.quiz_lti.exists?) + (respond_to?(:quizzes) && quizzes.active.exists?) || + (respond_to?(:assignments) && assignments.active.quiz_lti.exists?) }, - assignments: -> { self.respond_to?(:assignments) && self.assignments.active.exists? }, - pages: -> { self.respond_to?(:wiki_pages) && self.wiki_pages.active.exists? }, - conferences: -> { self.respond_to?(:web_conferences) && self.web_conferences.active.exists? }, - announcements: -> { self.respond_to?(:announcements) && self.announcements.active.exists? }, - outcomes: -> { self.respond_to?(:has_outcomes?) && self.has_outcomes? }, - discussions: -> { self.respond_to?(:discussion_topics) && self.discussion_topics.only_discussion_topics.except(:preload).exists? } + assignments: -> { respond_to?(:assignments) && assignments.active.exists? }, + pages: -> { respond_to?(:wiki_pages) && wiki_pages.active.exists? }, + conferences: -> { respond_to?(:web_conferences) && web_conferences.active.exists? }, + announcements: -> { respond_to?(:announcements) && announcements.active.exists? }, + outcomes: -> { respond_to?(:has_outcomes?) && has_outcomes? }, + discussions: -> { respond_to?(:discussion_topics) && discussion_topics.only_discussion_topics.except(:preload).exists? } } types_to_check = if only_check @@ -351,7 +351,7 @@ def feature_enabled?(_feature) end def nickname_for(_user, fallback = :name, prefer_friendly_name: true) - self.send fallback if fallback + send fallback if fallback end def self.last_updated_at(klasses_to_ids) @@ -376,6 +376,6 @@ def self.last_updated_at(klasses_to_ids) end def resolved_root_account_id - self.root_account_id if self.respond_to? :root_account_id + root_account_id if respond_to? :root_account_id end end diff --git a/app/models/context_external_tool.rb b/app/models/context_external_tool.rb index 5e961f875b161..ab0df2104d19e 100644 --- a/app/models/context_external_tool.rb +++ b/app/models/context_external_tool.rb @@ -73,7 +73,7 @@ class ContextExternalTool < ActiveRecord::Base end set_policy do - given { |user, session| self.context.grants_right?(user, session, :lti_add_edit) } + given { |user, session| context.grants_right?(user, session, :lti_add_edit) } can :read and can :update and can :delete and can :update_manually end @@ -224,11 +224,11 @@ def self.tool_for_assignment(assignment) return unless tag launch_url = assignment.external_tool_tag.url - self.find_external_tool(launch_url, assignment.context) + find_external_tool(launch_url, assignment.context) end def deployment_id - "#{self.id}:#{Lti::Asset.opaque_identifier_for(self.context)}"[0..254] + "#{id}:#{Lti::Asset.opaque_identifier_for(context)}"[0..254] end def content_migration_configured? @@ -352,14 +352,14 @@ def has_placement?(type) # (LTI 2 tools also, but those are not handled by this class) if developer_key_id.blank? && Lti::ResourcePlacement::LEGACY_DEFAULT_PLACEMENTS.include?(type.to_s) - !!(self.selectable && (self.domain || self.url)) + !!(selectable && (domain || url)) else - self.context_external_tool_placements.to_a.any? { |p| p.placement_type == type.to_s } + context_external_tool_placements.to_a.any? { |p| p.placement_type == type.to_s } end end def can_be_rce_favorite? - !self.editor_button.nil? + !editor_button.nil? end def is_rce_favorite_in_context?(context) @@ -367,23 +367,23 @@ def is_rce_favorite_in_context?(context) context = context.account if context.is_a?(Course) rce_favorite_tool_ids = context.rce_favorite_tool_ids[:value] if rce_favorite_tool_ids - rce_favorite_tool_ids.include?(self.global_id) + rce_favorite_tool_ids.include?(global_id) else # TODO remove after the datafixup and this column is dropped - self.is_rce_favorite + is_rce_favorite end end def sync_placements!(placements) - self.context_external_tool_placements.reload if self.context_external_tool_placements.loaded? - old_placements = self.context_external_tool_placements.pluck(:placement_type) + context_external_tool_placements.reload if context_external_tool_placements.loaded? + old_placements = context_external_tool_placements.pluck(:placement_type) placements_to_delete = Lti::ResourcePlacement::PLACEMENTS.map(&:to_s) - placements if placements_to_delete.any? - self.context_external_tool_placements.where(placement_type: placements_to_delete).delete_all if self.persisted? - self.context_external_tool_placements.reload if self.context_external_tool_placements.loaded? + context_external_tool_placements.where(placement_type: placements_to_delete).delete_all if persisted? + context_external_tool_placements.reload if context_external_tool_placements.loaded? end (placements - old_placements).each do |new_placement| - self.context_external_tool_placements.new(:placement_type => new_placement) + context_external_tool_placements.new(:placement_type => new_placement) end end private :sync_placements! @@ -456,7 +456,7 @@ def privacy_level=(val) end def privacy_level - self.workflow_state + workflow_state end def custom_fields_string @@ -474,10 +474,10 @@ def vendor_help_link=(val) end def validate_vendor_help_link - return if self.vendor_help_link.blank? + return if vendor_help_link.blank? begin - _value, uri = CanvasHttp.validate_url(self.vendor_help_link) + _value, uri = CanvasHttp.validate_url(vendor_help_link) self.vendor_help_link = uri.to_s rescue URI::Error, ArgumentError self.vendor_help_link = nil @@ -526,7 +526,7 @@ def process_extended_configuration converter.convert_blti_xml(config_xml) end - real_name = self.name + real_name = name if tool_hash[:error] @config_errors << [error_field, tool_hash[:error]] else @@ -675,8 +675,8 @@ def infer_defaults self.url = nil if url.blank? self.domain = nil if domain.blank? self.root_account ||= context.root_account - self.is_rce_favorite &&= self.can_be_rce_favorite? - ContextExternalTool.normalize_sizes!(self.settings) + self.is_rce_favorite &&= can_be_rce_favorite? + ContextExternalTool.normalize_sizes!(settings) Lti::ResourcePlacement::PLACEMENTS.each do |type| next unless settings[type] @@ -699,7 +699,7 @@ def change_domain!(new_domain) uri.to_s end - self.domain = new_domain if self.domain + self.domain = new_domain if domain self.url = replace_host.call(self.url, new_domain) if self.url @@ -757,7 +757,7 @@ def precedence def standard_url unless defined?(@standard_url) - @standard_url = !self.url.blank? && ContextExternalTool.standardize_url(self.url) + @standard_url = !url.blank? && ContextExternalTool.standardize_url(url) end @standard_url end @@ -820,7 +820,7 @@ def matches_domain?(url) end def duplicated_in_context? - duplicate_tool = self.class.find_external_tool(url, context, nil, self.id) + duplicate_tool = self.class.find_external_tool(url, context, nil, id) # If tool with same launch URL is found in the context return true if url.present? && duplicate_tool.present? @@ -890,15 +890,15 @@ def self.all_tools_for(context, options = {}) end def self.find_active_external_tool_by_consumer_key(consumer_key, context) - self.active.where(consumer_key: consumer_key, context: contexts_to_search(context)).first + active.where(consumer_key: consumer_key, context: contexts_to_search(context)).first end def self.find_active_external_tool_by_client_id(client_id, context) - self.active.where(developer_key_id: client_id, context: contexts_to_search(context)).first + active.where(developer_key_id: client_id, context: contexts_to_search(context)).first end def self.find_external_tool_by_id(id, context) - self.where(id: id, context: contexts_to_search(context)).first + where(id: id, context: contexts_to_search(context)).first end # Order of precedence: Basic LTI defines precedence as first @@ -1124,7 +1124,7 @@ def resource_selection_settings end def opaque_identifier_for(asset, context: nil) - ContextExternalTool.opaque_identifier_for(asset, self.shard, context: context) + ContextExternalTool.opaque_identifier_for(asset, shard, context: context) end def self.opaque_identifier_for(asset, shard, context: nil) @@ -1137,13 +1137,13 @@ def self.opaque_identifier_for(asset, shard, context: nil) end def visible_with_permission_check?(launch_type, user, context, session = nil) - return false unless self.class.visible?(self.extension_setting(launch_type, 'visibility'), user, context, session) + return false unless self.class.visible?(extension_setting(launch_type, 'visibility'), user, context, session) permission_given?(launch_type, user, context, session) end def permission_given?(launch_type, user, context, session = nil) - if (required_permissions_str = self.extension_setting(launch_type, 'required_permissions')) + if (required_permissions_str = extension_setting(launch_type, 'required_permissions')) # if configured with a comma-separated string of permissions, will only show the link # if all permissions are granted required_permissions_str.split(",").map(&:to_sym).all? do |p| @@ -1242,14 +1242,14 @@ def related_assignments(tool_id = nil) private def check_global_navigation_cache - if self.context.is_a?(Account) && self.context.root_account? - self.context.clear_cache_key(:global_navigation) # it's hard to know exactly _what_ changed so clear all initial global nav caches at once + if context.is_a?(Account) && context.root_account? + context.clear_cache_key(:global_navigation) # it's hard to know exactly _what_ changed so clear all initial global nav caches at once end end def clear_tool_domain_cache - if self.saved_change_to_domain? || self.saved_change_to_url? || self.saved_change_to_workflow_state? - self.context.clear_tool_domain_cache + if saved_change_to_domain? || saved_change_to_url? || saved_change_to_workflow_state? + context.clear_tool_domain_cache end end end diff --git a/app/models/context_module.rb b/app/models/context_module.rb index ebb0aa7cd28ff..4aee6024b9312 100644 --- a/app/models/context_module.rb +++ b/app/models/context_module.rb @@ -55,26 +55,26 @@ def relock_warning_check # then we're going to give the user an option to re-lock students out of the modules # otherwise they will be able to continue as before @relock_warning = false - return if self.new_record? + return if new_record? - if self.context.available? && self.active? - if self.saved_change_to_workflow_state? && self.workflow_state_before_last_save == "unpublished" + if context.available? && active? + if saved_change_to_workflow_state? && workflow_state_before_last_save == "unpublished" # should trigger when publishing a prerequisite for an already active module - @relock_warning = true if self.context.context_modules.active.any? { |mod| self.is_prerequisite_for?(mod) } + @relock_warning = true if context.context_modules.active.any? { |mod| is_prerequisite_for?(mod) } # if any of these changed while we were unpublished, then we also need to trigger - @relock_warning = true if self.prerequisites.any? || self.completion_requirements.any? || self.unlock_at.present? + @relock_warning = true if prerequisites.any? || completion_requirements.any? || unlock_at.present? end - if self.saved_change_to_completion_requirements? + if saved_change_to_completion_requirements? # removing a requirement shouldn't trigger - @relock_warning = true if (self.completion_requirements.to_a - self.completion_requirements_before_last_save.to_a).present? + @relock_warning = true if (completion_requirements.to_a - completion_requirements_before_last_save.to_a).present? end - if self.saved_change_to_prerequisites? + if saved_change_to_prerequisites? # ditto with removing a prerequisite - @relock_warning = true if (self.prerequisites.to_a - self.prerequisites_before_last_save.to_a).present? + @relock_warning = true if (prerequisites.to_a - prerequisites_before_last_save.to_a).present? end - if self.saved_change_to_unlock_at? + if saved_change_to_unlock_at? # adding a unlock_at date should trigger - @relock_warning = true if self.unlock_at.present? && self.unlock_at_before_last_save.blank? + @relock_warning = true if unlock_at.present? && unlock_at_before_last_save.blank? end end end @@ -88,15 +88,15 @@ def relock_progressions(relocked_modules = [], student_ids = nil) self.class.connection.after_transaction_commit do relocked_modules << self - progression_scope = self.context_module_progressions.where(:current => true).where.not(:workflow_state => 'locked') + progression_scope = context_module_progressions.where(:current => true).where.not(:workflow_state => 'locked') progression_scope = progression_scope.where(:user_id => student_ids) if student_ids if progression_scope.update_all(["workflow_state = 'locked', lock_version = lock_version + 1, current = ?", false]) > 0 - delay_if_production(strand: "module_reeval_#{self.global_context_id}").evaluate_all_progressions + delay_if_production(strand: "module_reeval_#{global_context_id}").evaluate_all_progressions end - self.context.context_modules.each do |mod| - mod.relock_progressions(relocked_modules, student_ids) if self.is_prerequisite_for?(mod) + context.context_modules.each do |mod| + mod.relock_progressions(relocked_modules, student_ids) if is_prerequisite_for?(mod) end end end @@ -105,10 +105,10 @@ def invalidate_progressions self.class.connection.after_transaction_commit do if context_module_progressions.where(current: true).update_all(current: false) > 0 # don't queue a job unless necessary - delay_if_production(strand: "module_reeval_#{self.global_context_id}").evaluate_all_progressions + delay_if_production(strand: "module_reeval_#{global_context_id}").evaluate_all_progressions end @discussion_topics_to_recalculate&.each do |dt| - dt.delay_if_production(strand: "module_reeval_#{self.global_context_id}").recalculate_context_module_actions! + dt.delay_if_production(strand: "module_reeval_#{global_context_id}").recalculate_context_module_actions! end end end @@ -118,23 +118,23 @@ def evaluate_all_progressions current_scope = context_module_progressions.where("#{current_column} IS NULL OR #{current_column} = ?", false).preload(:user) current_scope.find_in_batches(batch_size: 100) do |progressions| - self.context.cache_item_visibilities_for_user_ids(progressions.map(&:user_id)) + context.cache_item_visibilities_for_user_ids(progressions.map(&:user_id)) progressions.each do |progression| progression.context_module = self progression.evaluate! end - self.context.clear_cached_item_visibilities + context.clear_cached_item_visibilities end end def check_for_stale_cache_after_unlocking! - GuardRail.activate(:primary) { self.touch } if self.unlock_at && self.unlock_at < Time.now && self.updated_at < self.unlock_at + GuardRail.activate(:primary) { touch } if unlock_at && unlock_at < Time.now && updated_at < unlock_at end def is_prerequisite_for?(mod) - (mod.prerequisites || []).any? { |prereq| prereq[:type] == 'context_module' && prereq[:id] == self.id } + (mod.prerequisites || []).any? { |prereq| prereq[:type] == 'context_module' && prereq[:id] == id } end def self.module_positions(context) @@ -159,55 +159,55 @@ def remove_completion_requirement(id) end def infer_position - unless self.position - positions = ContextModule.module_positions(self.context) + unless position + positions = ContextModule.module_positions(context) self.position = if (max = positions.values.max) max + 1 else 1 end end - self.position + position end def get_potentially_conflicting_titles(title_base) - ContextModule.not_deleted.where(context_id: self.context_id) + ContextModule.not_deleted.where(context_id: context_id) .starting_with_name(title_base).pluck("name").to_set end def duplicate_base_model(copy_title) ContextModule.new({ - :context_id => self.context_id, - :context_type => self.context_type, + :context_id => context_id, + :context_type => context_type, :name => copy_title, - :position => ContextModule.not_deleted.where(context_id: self.context_id).maximum(:position) + 1, - :completion_requirements => self.completion_requirements, + :position => ContextModule.not_deleted.where(context_id: context_id).maximum(:position) + 1, + :completion_requirements => completion_requirements, :workflow_state => 'unpublished', - :require_sequential_progress => self.require_sequential_progress, - :completion_events => self.completion_events, - :requirement_count => self.requirement_count + :require_sequential_progress => require_sequential_progress, + :completion_events => completion_events, + :requirement_count => requirement_count }) end def can_be_duplicated? - self.content_tags.none? do |content_tag| + content_tags.none? do |content_tag| !content_tag.deleted? && content_tag.content_type_class == 'quiz' end end def send_items_to_stream - if self.saved_change_to_workflow_state? && self.workflow_state == 'active' - self.content_tags.where(content_type: "DiscussionTopic", workflow_state: 'active').preload(:content).each do |ct| + if saved_change_to_workflow_state? && workflow_state == 'active' + content_tags.where(content_type: "DiscussionTopic", workflow_state: 'active').preload(:content).each do |ct| ct.content.send_items_to_stream end end end def clear_discussion_stream_items - if self.saved_change_to_workflow_state? && - ['active', nil].include?(self.workflow_state_before_last_save) && - self.workflow_state == 'unpublished' - self.content_tags.where(content_type: "DiscussionTopic", workflow_state: 'active').preload(:content).each do |ct| + if saved_change_to_workflow_state? && + ['active', nil].include?(workflow_state_before_last_save) && + workflow_state == 'unpublished' + content_tags.where(content_type: "DiscussionTopic", workflow_state: 'active').preload(:content).each do |ct| ct.content.clear_stream_items end end @@ -256,9 +256,9 @@ def set_root_account_id end def duplicate - copy_title = get_copy_title(self, t("Copy"), self.name) + copy_title = get_copy_title(self, t("Copy"), name) new_module = duplicate_base_model(copy_title) - living_tags = self.content_tags.reject(&:deleted?) + living_tags = content_tags.reject(&:deleted?) new_module.content_tags = living_tags.map do |content_tag| duplicate_content_tag(content_tag) end @@ -266,10 +266,10 @@ def duplicate end def validate_prerequisites - positions = ContextModule.module_positions(self.context) + positions = ContextModule.module_positions(context) @already_confirmed_valid_requirements = false prereqs = [] - (self.prerequisites || []).each do |pre| + (prerequisites || []).each do |pre| if pre[:type] == 'context_module' position = positions[pre[:id].to_i] || 0 prereqs << pre if position && position < (self.position || 0) @@ -285,19 +285,19 @@ def validate_prerequisites def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - ContentTag.where(:context_module_id => self).where.not(:workflow_state => 'deleted').update_all(:workflow_state => 'deleted', :updated_at => self.deleted_at) + ContentTag.where(:context_module_id => self).where.not(:workflow_state => 'deleted').update_all(:workflow_state => 'deleted', :updated_at => deleted_at) delay_if_production(n_strand: "context_module_update_downstreams", priority: Delayed::LOW_PRIORITY).update_downstreams save! true end def restore - if self.workflow_state == 'deleted' && self.deleted_at + if workflow_state == 'deleted' && deleted_at # only restore tags deleted (approximately) when the module was deleted # (tags are currently set to exactly deleted_at but older deleted modules used the current time on each tag) - tags_to_restore = self.content_tags.where(:workflow_state => 'deleted') - .where('updated_at BETWEEN ? AND ?', self.deleted_at - 5.seconds, self.deleted_at + 5.seconds) - .preload(:content) + tags_to_restore = content_tags.where(:workflow_state => 'deleted') + .where('updated_at BETWEEN ? AND ?', deleted_at - 5.seconds, deleted_at + 5.seconds) + .preload(:content) tags_to_restore.each do |tag| # don't restore the item if the asset has been deleted too next if tag.asset_workflow_state == 'deleted' @@ -314,15 +314,15 @@ def restore end end self.workflow_state = 'unpublished' - self.save + save end def update_downstreams(_original_position = nil) # TODO: remove the unused argument; it's not sent anymore, but it was sent through a delayed job # so compatibility was maintained when sender was updated to not send it - positions = ContextModule.module_positions(self.context).to_a.sort_by { |a| a[1] } - downstream_ids = positions.select { |a| a[1] > (self.position || 0) }.map { |a| a[0] } - downstreams = downstream_ids.empty? ? [] : self.context.context_modules.not_deleted.where(id: downstream_ids) + positions = ContextModule.module_positions(context).to_a.sort_by { |a| a[1] } + downstream_ids = positions.select { |a| a[1] > (position || 0) }.map { |a| a[0] } + downstreams = downstream_ids.empty? ? [] : context.context_modules.not_deleted.where(id: downstream_ids) downstreams.each(&:save_without_touching_context) end @@ -345,7 +345,7 @@ def update_downstreams(_original_position = nil) alias_method :published?, :active? def publish_items! - self.content_tags.each do |tag| + content_tags.each do |tag| if tag.unpublished? if tag.content_type == 'Attachment' tag.content.set_publish_state_for_usage_rights @@ -360,23 +360,23 @@ def publish_items! end set_policy do - given { |user, session| self.context.grants_right?(user, session, :manage_content) } + given { |user, session| context.grants_right?(user, session, :manage_content) } can :read and can :create and can :update and can :delete and can :read_as_admin - given { |user, session| self.context.grants_right?(user, session, :read_as_admin) } + given { |user, session| context.grants_right?(user, session, :read_as_admin) } can :read and can :read_as_admin - given { |user, session| self.context.grants_right?(user, session, :view_unpublished_items) } + given { |user, session| context.grants_right?(user, session, :view_unpublished_items) } can :view_unpublished_items - given { |user, session| self.context.grants_right?(user, session, :read) && self.active? } + given { |user, session| context.grants_right?(user, session, :read) && active? } can :read end def low_level_locked_for?(user, opts = {}) - return false if self.grants_right?(user, :read_as_admin) + return false if grants_right?(user, :read_as_admin) - available = self.available_for?(user, opts) + available = available_for?(user, opts) return { object: self, module: self } unless available return { object: self, module: self, unlock_at: unlock_at } if to_be_unlocked @@ -384,34 +384,34 @@ def low_level_locked_for?(user, opts = {}) end def available_for?(user, opts = {}) - return true if self.active? && !self.to_be_unlocked && self.prerequisites.blank? && - (self.completion_requirements.empty? || !self.require_sequential_progress) - if self.grants_right?(user, :read_as_admin) + return true if active? && !to_be_unlocked && prerequisites.blank? && + (completion_requirements.empty? || !require_sequential_progress) + if grants_right?(user, :read_as_admin) return true - elsif !self.active? + elsif !active? return false - elsif self.context.user_has_been_observer?(user) # rubocop:disable Lint/DuplicateBranch + elsif context.user_has_been_observer?(user) # rubocop:disable Lint/DuplicateBranch return true end progression = if opts[:user_context_module_progressions] - opts[:user_context_module_progressions][self.id] + opts[:user_context_module_progressions][id] end - progression ||= self.find_or_create_progression(user) + progression ||= find_or_create_progression(user) # if the progression is locked, then position in the progression doesn't # matter. we're not available. tag = opts[:tag] avail = progression && !progression.locked? && !locked_for_tag?(tag, progression) if !avail && opts[:deep_check_if_needed] - progression = self.evaluate_for(progression) + progression = evaluate_for(progression) avail = progression && !progression.locked? && !locked_for_tag?(tag, progression) end avail end def locked_for_tag?(tag, progression) - locked = (tag&.context_module_id == self.id && self.require_sequential_progress) + locked = (tag&.context_module_id == id && require_sequential_progress) locked && (progression.current_position&.< tag.position) end @@ -434,11 +434,11 @@ def self.gather_module_names(scope) end def prerequisites - @prerequisites ||= gather_prerequisites(ContextModule.module_names(self.context)) + @prerequisites ||= gather_prerequisites(ContextModule.module_names(context)) end def active_prerequisites - @active_prerequisites ||= gather_prerequisites(ContextModule.active_module_names(self.context)) + @active_prerequisites ||= gather_prerequisites(ContextModule.active_module_names(context)) end def gather_prerequisites(module_names) @@ -458,7 +458,7 @@ def prerequisites=(prereqs) end when String res = [] - module_names = ContextModule.module_names(self.context) + module_names = ContextModule.module_names(context) pres = prereqs.split(",") pre_regex = /module_(\d+)/ pres.each do |pre| @@ -510,7 +510,7 @@ def validate_completion_requirements(requirements) new_req end - tags = self.content_tags.not_deleted.index_by(&:id) + tags = content_tags.not_deleted.index_by(&:id) validated_reqs = requirements.select do |req| if req[:id] && (tag = tags[req[:id]]) if %w[must_view must_mark_done must_contribute].include?(req[:type]) @@ -521,8 +521,8 @@ def validate_completion_requirements(requirements) end end - unless self.new_record? - old_requirements = self.completion_requirements || [] + unless new_record? + old_requirements = completion_requirements || [] validated_reqs.each do |req| if req[:type] == 'must_contribute' && !old_requirements.detect { |r| r[:id] == req[:id] && r[:type] == req[:type] } # new requirement tag = tags[req[:id]] @@ -545,7 +545,7 @@ def completion_requirements_visible_to(user, opts = {}) def content_tags_visible_to(user, opts = {}) @content_tags_visible_to ||= {} @content_tags_visible_to[user.try(:id)] ||= begin - is_teacher = opts[:is_teacher] != false && self.grants_right?(user, :read_as_admin) + is_teacher = opts[:is_teacher] != false && grants_right?(user, :read_as_admin) tags = is_teacher ? cached_not_deleted_tags : cached_active_tags if !is_teacher && user @@ -560,9 +560,9 @@ def content_tags_visible_to(user, opts = {}) def visibility_for_user(user, session = nil) opts = {} - opts[:can_read] = self.context.grants_right?(user, session, :read) + opts[:can_read] = context.grants_right?(user, session, :read) if opts[:can_read] - opts[:can_read_as_admin] = self.context.grants_right?(user, session, :read_as_admin) + opts[:can_read_as_admin] = context.grants_right?(user, session, :read_as_admin) end opts end @@ -583,7 +583,7 @@ def filter_tags_for_da(tags, user, opts = {}) :quiz end if item_type - visible_item_ids[item_type] ||= self.context.visible_item_ids_for_users(item_type, user_ids) # don't load the visibilities if there are no items of that type + visible_item_ids[item_type] ||= context.visible_item_ids_for_users(item_type, user_ids) # don't load the visibilities if there are no items of that type visible_item_ids[item_type].include?(tag.content_id) else true @@ -592,8 +592,8 @@ def filter_tags_for_da(tags, user, opts = {}) end shard.activate do - DifferentiableAssignment.filter(tags, user, self.context, opts) do |ts, user_ids| - filter.call(ts, user_ids, self.context_id, opts) + DifferentiableAssignment.filter(tags, user, context, opts) do |ts, user_ids| + filter.call(ts, user_ids, context_id, opts) end end end @@ -612,46 +612,46 @@ def clear_cached_lookups end def cached_active_tags - @cached_active_tags ||= if self.content_tags.loaded? + @cached_active_tags ||= if content_tags.loaded? # don't reload the preloaded content - self.content_tags.select(&:active?) + content_tags.select(&:active?) else - self.content_tags.active.to_a + content_tags.active.to_a end end def cached_not_deleted_tags - @cached_not_deleted_tags ||= if self.content_tags.loaded? + @cached_not_deleted_tags ||= if content_tags.loaded? # don't reload the preloaded content - self.content_tags.reject(&:deleted?) + content_tags.reject(&:deleted?) else - self.content_tags.not_deleted.to_a + content_tags.not_deleted.to_a end end def add_item(params, added_item = nil, opts = {}) params[:type] = params[:type].underscore if params[:type] - position = opts[:position] || ((self.content_tags.not_deleted.maximum(:position) || 0) + 1) + position = opts[:position] || ((content_tags.not_deleted.maximum(:position) || 0) + 1) position = [position, params[:position].to_i].max if params[:position] case params[:type] when "wiki_page", "page" - item = opts[:wiki_page] || self.context.wiki_pages.where(id: params[:id]).first + item = opts[:wiki_page] || context.wiki_pages.where(id: params[:id]).first when "attachment", "file" - item = opts[:attachment] || self.context.attachments.not_deleted.find_by(id: params[:id]) + item = opts[:attachment] || context.attachments.not_deleted.find_by(id: params[:id]) when "assignment" - item = opts[:assignment] || self.context.assignments.active.where(id: params[:id]).first + item = opts[:assignment] || context.assignments.active.where(id: params[:id]).first item = item.submittable_object if item.respond_to?(:submittable_object) && item.submittable_object when "discussion_topic", "discussion" - item = opts[:discussion_topic] || self.context.discussion_topics.active.where(id: params[:id]).first + item = opts[:discussion_topic] || context.discussion_topics.active.where(id: params[:id]).first when "quiz" - item = opts[:quiz] || self.context.quizzes.active.where(id: params[:id]).first + item = opts[:quiz] || context.quizzes.active.where(id: params[:id]).first end workflow_state = ContentTag.asset_workflow_state(item) if item workflow_state ||= 'active' case params[:type] when 'external_url' title = params[:title] - added_item ||= self.content_tags.build(:context => self.context) + added_item ||= content_tags.build(:context => context) added_item.attributes = { :url => params[:url], :new_tab => params[:new_tab], @@ -662,17 +662,17 @@ def add_item(params, added_item = nil, opts = {}) } added_item.content_id = 0 added_item.content_type = 'ExternalUrl' - added_item.context_module_id = self.id + added_item.context_module_id = id added_item.indent = params[:indent] || 0 added_item.workflow_state = 'unpublished' if added_item.new_record? when 'context_external_tool', 'external_tool', 'lti/message_handler' title = params[:title] - added_item ||= self.content_tags.build(:context => self.context) + added_item ||= content_tags.build(:context => context) content = if params[:type] == 'lti/message_handler' Lti::MessageHandler.for_context(context).where(id: params[:id]).first else - ContextExternalTool.find_external_tool(params[:url], self.context, params[:id].to_i) || ContextExternalTool.new.tap { |tool| tool.id = 0 } + ContextExternalTool.find_external_tool(params[:url], context, params[:id].to_i) || ContextExternalTool.new.tap { |tool| tool.id = 0 } end added_item.attributes = { content: content, @@ -683,7 +683,7 @@ def add_item(params, added_item = nil, opts = {}) :indent => params[:indent], :position => position } - added_item.context_module_id = self.id + added_item.context_module_id = id added_item.indent = params[:indent] || 0 added_item.workflow_state = 'unpublished' if added_item.new_record? added_item.link_settings = params[:link_settings] @@ -704,7 +704,7 @@ def add_item(params, added_item = nil, opts = {}) end when 'context_module_sub_header', 'sub_header' title = params[:title] - added_item ||= self.content_tags.build(:context => self.context) + added_item ||= content_tags.build(:context => context) added_item.attributes = { :tag_type => 'context_module', :title => title, @@ -713,14 +713,14 @@ def add_item(params, added_item = nil, opts = {}) } added_item.content_id = 0 added_item.content_type = 'ContextModuleSubHeader' - added_item.context_module_id = self.id + added_item.context_module_id = id added_item.indent = params[:indent] || 0 added_item.workflow_state = 'unpublished' if added_item.new_record? else return nil unless item title = params[:title] || (item.title rescue item.name) - added_item ||= self.content_tags.build(:context => context) + added_item ||= content_tags.build(:context => context) added_item.attributes = { :content => item, :tag_type => 'context_module', @@ -728,7 +728,7 @@ def add_item(params, added_item = nil, opts = {}) :indent => params[:indent], :position => position } - added_item.context_module_id = self.id + added_item.context_module_id = id added_item.indent = params[:indent] || 0 added_item.workflow_state = workflow_state if added_item.new_record? end @@ -756,9 +756,9 @@ def insert_items(items, start_pos = nil) next if tags.any? { |tag| tag.content_type == item.class_name && tag.content_id == item.id } state = item.respond_to?(:published?) && !item.published? ? 'unpublished' : 'active' - new_tags << self.content_tags.create!(context: self.context, title: Context.asset_name(item), content: item, - tag_type: 'context_module', indent: 0, - position: next_pos, workflow_state: state) + new_tags << content_tags.create!(context: context, title: Context.asset_name(item), content: item, + tag_type: 'context_module', indent: 0, + position: next_pos, workflow_state: state) next_pos += 1 end @@ -781,8 +781,8 @@ def insert_items(items, start_pos = nil) end def update_for(user, action, tag, points = nil) - return nil unless self.context.grants_right?(user, :participate_as_student) - return nil unless (progression = self.evaluate_for(user)) + return nil unless context.grants_right?(user, :participate_as_student) + return nil unless (progression = evaluate_for(user)) return nil if progression.locked? progression.update_requirement_met!(action, tag, points) @@ -790,7 +790,7 @@ def update_for(user, action, tag, points = nil) end def completion_requirement_for(action, tag) - self.completion_requirements.to_a.find do |requirement| + completion_requirements.to_a.find do |requirement| next false unless requirement[:id] == tag.local_id case requirement[:type] @@ -831,16 +831,16 @@ def confirm_valid_requirements(do_save = false) @already_confirmed_valid_requirements = true # the write accessor validates for us - self.completion_requirements = self.completion_requirements || [] - self.save if do_save && self.completion_requirements_changed? - self.completion_requirements + self.completion_requirements = completion_requirements || [] + save if do_save && completion_requirements_changed? + completion_requirements end def find_or_create_progressions(users) users = Array(users) users_hash = {} users.each { |u| users_hash[u.id] = u } - progressions = self.context_module_progressions.where(user_id: users) + progressions = context_module_progressions.where(user_id: users) progressions_hash = {} progressions.each { |p| progressions_hash[p.user_id] = p } newbies = users.reject { |u| progressions_hash[u.id] } @@ -853,7 +853,7 @@ def find_or_create_progression(user) return nil unless user progression = nil - self.shard.activate do + shard.activate do GuardRail.activate(:primary) do progression = context_module_progressions.where(user_id: user).first if !progression && context.enrollments.except(:preload).where(user_id: user).exists? # check if we should even be creating a progression for this user @@ -872,18 +872,18 @@ def evaluate_for(user_or_progression) if user_or_progression.is_a?(ContextModuleProgression) progression, user = [user_or_progression, user_or_progression.user] else - progression, user = [self.find_or_create_progression(user_or_progression), user_or_progression] if user_or_progression + progression, user = [find_or_create_progression(user_or_progression), user_or_progression] if user_or_progression end return nil unless progression && user - progression.context_module = self if progression.context_module_id == self.id + progression.context_module = self if progression.context_module_id == id progression.user = user if progression.user_id == user.id progression.evaluate! end def to_be_unlocked - self.unlock_at && self.unlock_at > Time.now + unlock_at && unlock_at > Time.now end def migration_position @@ -908,7 +908,7 @@ def completion_events=(value) end VALID_COMPLETION_EVENTS.each do |event| - self.class_eval <<~RUBY, __FILE__, __LINE__ + 1 + class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{event}=(value) if Canvas::Plugin.value_to_boolean(value) self.completion_events |= [:#{event}] diff --git a/app/models/context_module_item.rb b/app/models/context_module_item.rb index 3c975fce1351a..0385768af4f58 100644 --- a/app/models/context_module_item.rb +++ b/app/models/context_module_item.rb @@ -33,8 +33,8 @@ def self.included(klass) # If we are locked, this will return the module item (ContentTag) that is # locking the item for the given user def locked_by_module_item?(user, opts = {}) - if self.context_module_tags.present? && self.context_module_tags.all? { |tag| tag.locked_for?(user, opts) } - item = self.context_module_tags.first + if context_module_tags.present? && context_module_tags.all? { |tag| tag.locked_for?(user, opts) } + item = context_module_tags.first end item || false end diff --git a/app/models/context_module_progression.rb b/app/models/context_module_progression.rb index 53e7006f0260e..5f2699e0430f1 100644 --- a/app/models/context_module_progression.rb +++ b/app/models/context_module_progression.rb @@ -41,7 +41,7 @@ def completion_requirements private :completion_requirements def set_completed_at - if self.completed? + if completed? self.completed_at ||= Time.now else self.completed_at = nil @@ -49,11 +49,11 @@ def set_completed_at end def set_root_account_id - self.root_account_id = self.context_module.root_account_id + self.root_account_id = context_module.root_account_id end def finished_item?(item) - (self.requirements_met || []).any? { |r| r[:id] == item.id } + (requirements_met || []).any? { |r| r[:id] == item.id } end def collapse!(skip_save: false) @@ -67,15 +67,15 @@ def uncollapse!(skip_save: false) def update_collapse_state(collapsed_target_state, skip_save: false) retry_count = 0 begin - return if self.collapsed == collapsed_target_state + return if collapsed == collapsed_target_state self.collapsed = collapsed_target_state - self.save unless skip_save + save unless skip_save rescue ActiveRecord::StaleObjectError => e Canvas::Errors.capture_exception(:context_modules, e, :info) retry_count += 1 if retry_count < 5 - self.reload + reload retry else raise @@ -87,7 +87,7 @@ def update_collapse_state(collapsed_target_state, skip_save: false) def uncomplete_requirement(id) requirement = requirements_met.find { |r| r[:id] == id } requirements_met.delete(requirement) - self.remove_incomplete_requirement(id) + remove_incomplete_requirement(id) mark_as_outdated end @@ -114,7 +114,7 @@ def initialize(actions_done) end def sorted_action_keys - self.actions_done.map { |r| "#{r[:id]}_#{r[:type]}" }.sort + actions_done.map { |r| "#{r[:id]}_#{r[:type]}" }.sort end def increment_met_requirement_count! @@ -122,7 +122,7 @@ def increment_met_requirement_count! end def requirement_met?(req, include_type = true) - self.actions_done.any? { |r| r[:id] == req[:id] && (include_type ? r[:type] == req[:type] : true) } + actions_done.any? { |r| r[:id] == req[:id] && (include_type ? r[:type] == req[:type] : true) } end def check_action!(action, is_met) @@ -135,15 +135,15 @@ def check_action!(action, is_met) def add_done_action!(action) increment_met_requirement_count! - self.actions_done << action + actions_done << action end def add_view_requirement(req) - self.view_requirements << req + view_requirements << req end def check_view_requirements - self.view_requirements.each do |req| + view_requirements.each do |req| # should mark a must_view as true if a completed must_submit/min_score action already exists check_action!(req, requirement_met?(req, false)) end @@ -153,11 +153,11 @@ def check_view_requirements def evaluate_requirements_met result = evaluate_uncompleted_requirements - count_needed = self.context_module.requirement_count.to_i + count_needed = context_module.requirement_count.to_i # if no requirement_count is specified, assume all are needed self.workflow_state = if (count_needed && count_needed > 0 && result.met_requirement_count >= count_needed) || result.all_met? 'completed' - elsif result.met_requirement_count >= 1 || self.incomplete_requirements.count >= 1 # submitting to a min_score requirement should move it to started + elsif result.met_requirement_count >= 1 || incomplete_requirements.count >= 1 # submitting to a min_score requirement should move it to started 'started' else 'unlocked' @@ -171,14 +171,14 @@ def evaluate_requirements_met def evaluate_uncompleted_requirements tags_hash = nil - calc = CompletedRequirementCalculator.new(self.requirements_met || []) + calc = CompletedRequirementCalculator.new(requirements_met || []) self.incomplete_requirements = [] # start from a clean slate completion_requirements.each do |req| # for an observer/student user we don't want to filter based on the normal observer logic, # instead return vis for student enrollment only -> hence ignore_observer_logic below # create the hash inside the loop in case the completion_requirements is empty (performance) - tags_hash ||= context_module.content_tags_visible_to(self.user, is_teacher: false, ignore_observer_logic: true).index_by(&:id) + tags_hash ||= context_module.content_tags_visible_to(user, is_teacher: false, ignore_observer_logic: true).index_by(&:id) tag = tags_hash[req[:id]] next unless tag @@ -245,17 +245,17 @@ def get_submission_score(submission) private :get_submission_score def remove_incomplete_requirement(requirement_id) - self.incomplete_requirements.delete_if { |r| r[:id] == requirement_id } + incomplete_requirements.delete_if { |r| r[:id] == requirement_id } end # hold onto the status of the incomplete min_score requirement def update_incomplete_requirement!(requirement, score) return unless requirement[:type] == "min_score" - incomplete_req = self.incomplete_requirements.detect { |r| r[:id] == requirement[:id] } + incomplete_req = incomplete_requirements.detect { |r| r[:id] == requirement[:id] } unless incomplete_req incomplete_req = requirement.dup - self.incomplete_requirements << incomplete_req + incomplete_requirements << incomplete_req end if incomplete_req[:score].nil? incomplete_req[:score] = score @@ -272,7 +272,7 @@ def evaluate_score_requirement_met(requirement, subs) if (unposted_sub = subs.detect { |sub| sub.is_a?(Submission) && !sub.posted? }) # don't mark the progress as in-progress if they haven't submitted - self.update_incomplete_requirement!(requirement, nil) unless unposted_sub.unsubmitted? + update_incomplete_requirement!(requirement, nil) unless unposted_sub.unsubmitted? return end @@ -283,7 +283,7 @@ def evaluate_score_requirement_met(requirement, subs) remove_incomplete_requirement(requirement[:id]) else unless sub.is_a?(Submission) && sub.unsubmitted? - self.update_incomplete_requirement!(requirement, score) # hold onto the score if requirement not met + update_incomplete_requirement!(requirement, score) # hold onto the score if requirement not met end end requirement_met @@ -300,12 +300,12 @@ def update_requirement_met(action, tag, points = nil) requirement_met = false if requirement[:type] == 'must_submit' # calculate later; requires the submission if !requirement_met - self.requirements_met.delete(requirement) - self.mark_as_outdated + requirements_met.delete(requirement) + mark_as_outdated true - elsif !self.requirements_met.include?(requirement) - self.requirements_met.push(requirement) - self.mark_as_outdated + elsif !requirements_met.include?(requirement) + requirements_met.push(requirement) + mark_as_outdated true else false @@ -315,13 +315,13 @@ def update_requirement_met(action, tag, points = nil) def update_requirement_met!(*args) retry_count = 0 begin - if self.update_requirement_met(*args) - self.save! + if update_requirement_met(*args) + save! delay_if_production.evaluate! end rescue ActiveRecord::StaleObjectError # retry up to five times, otherwise return current (stale) data - self.reload + reload retry_count += 1 if retry_count < 5 retry @@ -336,19 +336,19 @@ def mark_as_outdated end def mark_as_outdated! - if self.new_record? + if new_record? mark_as_outdated GuardRail.activate(:primary) do - self.save! + save! end else self.class.where(:id => self).update_all(:current => false) - self.touch_user + touch_user end end def outdated? - if self.current && evaluated_at.present? + if current && evaluated_at.present? return true if evaluated_at < context_module.updated_at # context module not locked or still to be unlocked @@ -381,10 +381,10 @@ def prerequisites_satisfied? def check_prerequisites return false if context_module.to_be_unlocked - if self.locked? + if locked? self.workflow_state = 'unlocked' if prerequisites_satisfied? end - !self.locked? + !locked? end private :check_prerequisites @@ -397,7 +397,7 @@ def evaluate_current_position # for an observer/student combo user we don't want to filter based on the # normal observer logic, instead return vis for student enrollment only - context_module.content_tags_visible_to(self.user, is_teacher: false, ignore_observer_logic: true).each do |tag| + context_module.content_tags_visible_to(user, is_teacher: false, ignore_observer_logic: true).each do |tag| self.current_position = tag.position if tag.position all_met = completion_requirements.select { |r| r[:id] == tag.id }.all? do |req| requirements_met.any? { |r| r[:id] == req[:id] && r[:type] == req[:type] } @@ -416,11 +416,11 @@ def evaluate!(as_prerequisite_for = nil) evaluate(as_prerequisite_for) rescue ActiveRecord::StaleObjectError # retry up to five times, otherwise return current (stale) data - self.reload + reload retry_count += 1 retry if retry_count < 10 - logger.error { "Failed to evaluate stale progression: #{self.inspect}" } + logger.error { "Failed to evaluate stale progression: #{inspect}" } end self @@ -429,7 +429,7 @@ def evaluate!(as_prerequisite_for = nil) # calculates and saves the progression state # raises a StaleObjectError if there is a conflict def evaluate(as_prerequisite_for = nil) - self.shard.activate do + shard.activate do return self unless outdated? # there is no valid progression state for unpublished modules @@ -442,17 +442,17 @@ def evaluate(as_prerequisite_for = nil) if check_prerequisites evaluate_requirements_met end - completion_changed = self.workflow_state_changed? && self.workflow_state_change.include?('completed') + completion_changed = workflow_state_changed? && workflow_state_change.include?('completed') evaluate_current_position GuardRail.activate(:primary) do - self.save + save end if completion_changed trigger_reevaluation_of_dependent_progressions(as_prerequisite_for) - trigger_completion_events if self.completed? + trigger_completion_events if completed? end self @@ -467,7 +467,7 @@ def trigger_reevaluation_of_dependent_progressions(dependent_module_to_skip = ni # re-evaluating progressions that have requested our progression's evaluation can cause cyclic evaluation next false if dependent_module_to_skip && progression.context_module_id == dependent_module_to_skip.id - self.context_module.is_prerequisite_for?(progression.context_module) + context_module.is_prerequisite_for?(progression.context_module) end # invalidate all, then re-evaluate each diff --git a/app/models/conversation.rb b/app/models/conversation.rb index fe9a4319ae271..9b092765607f7 100644 --- a/app/models/conversation.rb +++ b/app/models/conversation.rb @@ -73,7 +73,7 @@ def self.private_hash_for(users_or_user_ids, context_code = nil) def bulk_insert_participants(user_ids, options = {}) options = { - :conversation_id => self.id, + :conversation_id => id, :workflow_state => 'read', :has_attachments => has_attachments?, :has_media_objects => has_media_objects?, @@ -142,7 +142,7 @@ def can_add_participants?(users) def add_participants(current_user, users, options = {}) message = nil - self.shard.activate do + shard.activate do user_ids = users.map(&:id).uniq raise "can't add participants to a private conversation" if private? @@ -155,7 +155,7 @@ def add_participants(current_user, users, options = {}) bulk_insert_options = { :workflow_state => 'unread', :message_count => 0, - :private_hash => self.private_hash + :private_hash => private_hash } else last_message_at = conversation_messages.human.first.try(:created_at) @@ -167,7 +167,7 @@ def add_participants(current_user, users, options = {}) :workflow_state => 'unread', :last_message_at => last_message_at, :message_count => num_messages, - :private_hash => self.private_hash + :private_hash => private_hash } end @@ -179,7 +179,7 @@ def add_participants(current_user, users, options = {}) end end - next if Shard.current == self.shard + next if Shard.current == shard bulk_insert_participants(shard_user_ids, bulk_insert_options) end @@ -189,7 +189,7 @@ def add_participants(current_user, users, options = {}) unless options[:no_messages] # give them all messages # NOTE: individual messages in group conversations don't have tags - self.class.connection.execute(sanitize_sql([<<~SQL.squish, self.id, current_user.id, user_ids])) + self.class.connection.execute(sanitize_sql([<<~SQL.squish, id, current_user.id, user_ids])) INSERT INTO #{ConversationMessageParticipant.quoted_table_name}(conversation_message_id, conversation_participant_id, user_id, workflow_state) SELECT conversation_messages.id, conversation_participants.id, conversation_participants.user_id, 'active' FROM #{ConversationMessage.quoted_table_name}, #{ConversationParticipant.quoted_table_name}, #{ConversationMessageParticipant.quoted_table_name} @@ -203,7 +203,7 @@ def add_participants(current_user, users, options = {}) # announce their arrival message = add_event_message(current_user, { :event_type => :users_added, :user_ids => user_ids }, options) end - self.touch + touch Canvas::LiveEvents.conversation_forwarded(self) end end @@ -253,8 +253,8 @@ def add_message(current_user, body_or_obj, options = {}) Conversation.build_message(current_user, body_or_obj, options) end message.conversation = self - message.relativize_attachment_ids(from_shard: message.shard, to_shard: self.shard) - message.shard = self.shard + message.relativize_attachment_ids(from_shard: message.shard, to_shard: shard) + message.shard = shard if options[:cc_author] message.cc_author = options[:cc_author] @@ -300,7 +300,7 @@ def add_message(current_user, body_or_obj, options = {}) end def reset_unread_counts - Shard.partition_by_shard(self.conversation_participants.pluck(:user_id)) do |shard_user_ids| + Shard.partition_by_shard(conversation_participants.pluck(:user_id)) do |shard_user_ids| shard_user_ids.compact.sort.each_slice(1000) do |sliced_ids| counts_by_user_id = ConversationParticipant.visible.unread.where(:user_id => sliced_ids).group(:user_id).count User.where(id: sliced_ids).select(:id, :unread_conversations_count).each do |user| @@ -361,7 +361,7 @@ def add_message_to_participants(message, options = {}) skip_participants = message.conversation_message_participants.active.select(:user_id).to_a end - self.conversation_participants.shard(self).activate do |cps| + conversation_participants.shard(self).activate do |cps| cps.update_all(:root_account_ids => options[:root_account_ids]) if options[:root_account_ids].present? cps = cps.visible if options[:only_existing] @@ -376,7 +376,7 @@ def add_message_to_participants(message, options = {}) cps.update_all("message_count = message_count + 1") unless options[:generated] - if self.shard == Shard.current + if shard == Shard.current users = options[:preloaded_users] || preload_users_and_context_codes current_context_strings(nil, users) @@ -396,7 +396,7 @@ def add_message_to_participants(message, options = {}) end cp.update_attribute(:tags, updated_tags) - if cp.user.shard != self.shard + if cp.user.shard != shard cp.user.shard.activate do ConversationParticipant.where(:conversation_id => self, :user_id => cp.user_id) .update_all(:tags => serialized_tags(cp.tags)) @@ -460,7 +460,7 @@ def infer_new_tags_for(participant, all_new_tags) # otherwise, use all of the available tags new_tags = visible_codes.presence || (current_context_strings & context_codes) - message_tags = if self.private? + message_tags = if private? if new_tags.present? new_tags elsif participant.message_count > 0 && (last_message = participant.last_message) @@ -473,7 +473,7 @@ def infer_new_tags_for(participant, all_new_tags) def update_participants(message, options = {}) updated = false - self.conversation_participants.shard(self).activate do |conversation_participants| + conversation_participants.shard(self).activate do |conversation_participants| conversation_participants = conversation_participants.where(:user_id => (options[:only_users]).map(&:id)) if options[:only_users] @@ -506,7 +506,7 @@ def update_participants(message, options = {}) updated = true end end - self.save if updated + save if updated end def subscribed_participants @@ -517,7 +517,7 @@ def subscribed_participants def reply_from(opts) user = opts.delete(:user) message = opts.delete(:text).to_s.strip - participant = self.conversation_participants.where(user_id: user).first + participant = conversation_participants.where(user_id: user).first user = nil unless user && participant if !user raise IncomingMail::Errors::InvalidParticipant @@ -561,10 +561,10 @@ def regenerate_private_hash!(user_ids = nil) return unless private? self.private_hash = Conversation.private_hash_for(user_ids || - Shard.birth.activate { self.conversation_participants.reload.map(&:user_id) }) + Shard.birth.activate { conversation_participants.reload.map(&:user_id) }) return unless private_hash_changed? - existing = self.shard.activate do + existing = shard.activate do ConversationParticipant.unscoped do ConversationParticipant.where(private_hash: private_hash).take&.conversation end @@ -573,8 +573,8 @@ def regenerate_private_hash!(user_ids = nil) merge_into(existing) else save! - Shard.with_each_shard(self.associated_shards) do - ConversationParticipant.where(:conversation_id => self).update_all(:private_hash => self.private_hash) + Shard.with_each_shard(associated_shards) do + ConversationParticipant.where(:conversation_id => self).update_all(:private_hash => private_hash) end end end @@ -603,7 +603,7 @@ def merge_into(other) # remove the duplicate participant cp.destroy - if cp.user.shard != self.shard + if cp.user.shard != shard # remove the duplicate secondary CP on the user's shard cp.user.shard.activate do ConversationParticipant.where(conversation_id: self, :user_id => cp.user_id).delete_all @@ -613,14 +613,14 @@ def merge_into(other) # keep the cp, with updated conversation, iff the source # conversation shared a shard with the user OR the target # conversation - if self.shard == other.shard || self.shard == cp.user.shard + if shard == other.shard || shard == cp.user.shard ConversationParticipant.where(id: cp).update_all(conversation_id: other.id) else cp.destroy end # update the duplicate cp on the user's shard if it's a different # shard - if cp.user.shard != self.shard + if cp.user.shard != shard cp.user.shard.activate do ConversationParticipant.where(:conversation_id => self, :user_id => cp.user_id) .update_all(conversation_id: other.id) @@ -629,7 +629,7 @@ def merge_into(other) # create a new duplicate cp on the target conversation's shard # if neither the user nor source conversation were there # already. - if self.shard != other.shard && cp.user.shard != other.shard + if shard != other.shard && cp.user.shard != other.shard new_cp = cp.clone new_cp.shard = other.shard new_cp.conversation = other @@ -638,14 +638,14 @@ def merge_into(other) end end end - if other.shard == self.shard + if other.shard == shard conversation_messages.update_all(conversation_id: other.id) else # move messages and participants over to new shard conversation_messages.find_each do |message| new_message = message.clone new_message.conversation = other - message.relativize_attachment_ids(from_shard: self.shard, to_shard: other.shard) + message.relativize_attachment_ids(from_shard: shard, to_shard: other.shard) new_message.shard = other.shard new_message.save! message.conversation_message_participants.find_each do |cmp| @@ -655,11 +655,11 @@ def merge_into(other) new_cmp.save! end end - self.shard.activate do + shard.activate do ConversationMessageParticipant.joins(:conversation_message) - .where(:conversation_messages => { :conversation_id => self.id }) + .where(:conversation_messages => { :conversation_id => id }) .delete_all - self.conversation_messages.delete_all + conversation_messages.delete_all end end @@ -676,7 +676,7 @@ def update_root_account_ids # ids must be sorted for the scope to work latest_ids = read_attribute(:root_account_ids) %w[conversation_participants conversation_messages conversation_message_participants].each do |assoc| - scope = self.send(assoc).where("#{assoc}.root_account_ids IS DISTINCT FROM ?", latest_ids).limit(1_000) + scope = send(assoc).where("#{assoc}.root_account_ids IS DISTINCT FROM ?", latest_ids).limit(1_000) until scope.update_all(root_account_ids: latest_ids) < 1_000; end end end @@ -761,17 +761,17 @@ def delete_for_all end def replies_locked_for?(user) - return false unless %w[Course Group].include?(self.context_type) + return false unless %w[Course Group].include?(context_type) - course = self.context.is_a?(Course) ? self.context : self.context.context + course = context.is_a?(Course) ? context : context.context # can still reply if a teacher is involved - if (course.is_a?(Course) && self.conversation_participants.where(:user_id => course.admin_enrollments.active.select(:user_id)).exists?) || + if (course.is_a?(Course) && conversation_participants.where(:user_id => course.admin_enrollments.active.select(:user_id)).exists?) || # can still reply if observing all the other participants (course.is_a?(Course) && observing_all_other_participants(user, course)) false else - !self.context.grants_any_right?(user, :send_messages, :send_messages_all) + !context.grants_any_right?(user, :send_messages, :send_messages_all) end end diff --git a/app/models/conversation_batch.rb b/app/models/conversation_batch.rb index 80f67cb8bdf31..75d72c1439d3c 100644 --- a/app/models/conversation_batch.rb +++ b/app/models/conversation_batch.rb @@ -38,13 +38,13 @@ class ConversationBatch < ActiveRecord::Base attr_reader :conversations def deliver(update_progress = true) - self.shard.activate do + shard.activate do chunk_size = 25 @conversations = [] self.user = user_map[user_id] - existing_conversations = Conversation.find_all_private_conversations(self.user, recipient_ids.map { |id| user_map[id] }, - context_type: self.context_type, context_id: self.context_id) + existing_conversations = Conversation.find_all_private_conversations(user, recipient_ids.map { |id| user_map[id] }, + context_type: context_type, context_id: context_id) update_attribute :workflow_state, 'sending' ModelCache.with_cache(:conversations => existing_conversations, :users => { :id => user_map }) do @@ -52,12 +52,12 @@ def deliver(update_progress = true) recipient_ids.each_slice(chunk_size) do |ids| ids.each do |id| - is_group = self.group? + is_group = group? conversation = user.initiate_conversation([user_map[id]], !is_group, subject: subject, context_type: context_type, context_id: context_id) @conversations << conversation message = root_conversation_message.clone - message.generate_user_note = self.generate_user_note + message.generate_user_note = generate_user_note conversation.add_message(message, update_for_sender: false, tags: tags, cc_author: should_cc_author) conversation_message_ids << message.id @@ -101,7 +101,7 @@ def completion attr_writer :user_map def user_map - @user_map ||= self.shard.activate { User.where(id: recipient_ids + [user_id]).index_by(&:id) } + @user_map ||= shard.activate { User.where(id: recipient_ids + [user_id]).index_by(&:id) } end def recipient_ids diff --git a/app/models/conversation_message.rb b/app/models/conversation_message.rb index af96849533d0d..cb238bc929b78 100644 --- a/app/models/conversation_message.rb +++ b/app/models/conversation_message.rb @@ -97,20 +97,20 @@ def self.preload_latest(conversation_participants, author = nil) has_a_broadcast_policy set_broadcast_policy do |p| p.dispatch :conversation_message - p.to { self.recipients } + p.to { recipients } p.whenever { |record| (record.just_created || @re_send_message) && !record.generated && !record.submission } p.dispatch :added_to_conversation - p.to { self.new_recipients } + p.to { new_recipients } p.whenever { |record| (record.just_created || @re_send_message) && record.generated && record.event_data[:event_type] == :users_added } p.dispatch :conversation_created - p.to { [self.author] } + p.to { [author] } p.whenever { |record| record.cc_author && ((record.just_created || @re_send_message) && !record.generated && !record.submission) } end on_create_send_to_streams do - self.recipients unless skip_broadcasts || submission # we still render them w/ the conversation in the stream item, we just don't cause it to jump to the top + recipients unless skip_broadcasts || submission # we still render them w/ the conversation in the stream item, we just don't cause it to jump to the top end def after_participants_created_broadcast @@ -125,13 +125,13 @@ def after_participants_created_broadcast before_destroy :delete_from_participants def infer_values - self.media_comment_id = nil if self.media_comment_id && self.media_comment_id.strip.empty? - if self.media_comment_id && self.media_comment_id_changed? - @media_comment = MediaObject.by_media_id(self.media_comment_id).first + self.media_comment_id = nil if media_comment_id && media_comment_id.strip.empty? + if media_comment_id && media_comment_id_changed? + @media_comment = MediaObject.by_media_id(media_comment_id).first self.media_comment_id = nil unless @media_comment self.media_comment_type = @media_comment.media_type if @media_comment end - self.media_comment_type = nil unless self.media_comment_id + self.media_comment_type = nil unless media_comment_id self.has_attachments = attachment_ids.present? || forwarded_messages.any?(&:has_attachments?) self.has_media_objects = media_comment_id.present? || forwarded_messages.any?(&:has_media_objects?) true @@ -152,17 +152,17 @@ def relativize_attachment_ids(from_shard:, to_shard:) end def attachments - self.attachment_associations.map(&:attachment) + attachment_associations.map(&:attachment) end def update_attachment_associations - previous_attachment_ids = self.attachment_associations.pluck(:attachment_id) + previous_attachment_ids = attachment_associations.pluck(:attachment_id) deleted_attachment_ids = previous_attachment_ids - attachment_ids new_attachment_ids = attachment_ids - previous_attachment_ids - self.attachment_associations.where(attachment_id: deleted_attachment_ids).find_each(&:destroy) + attachment_associations.where(attachment_id: deleted_attachment_ids).find_each(&:destroy) if new_attachment_ids.any? author.conversation_attachments_folder.attachments.where(id: new_attachment_ids).find_each do |attachment| - self.attachment_associations.create!(attachment: attachment) + attachment_associations.create!(attachment: attachment) end end end @@ -174,8 +174,8 @@ def delete_from_participants end def media_comment - if !@media_comment && self.media_comment_id - @media_comment = MediaObject.by_media_id(self.media_comment_id).first + if !@media_comment && media_comment_id + @media_comment = MediaObject.by_media_id(media_comment_id).first end @media_comment end @@ -189,7 +189,7 @@ def media_comment=(media_comment) def recipients return [] unless conversation - subscribed = subscribed_participants.reject { |u| u.id == self.author_id }.map { |x| x.becomes(User) } + subscribed = subscribed_participants.reject { |u| u.id == author_id }.map { |x| x.becomes(User) } ActiveRecord::Associations::Preloader.new.preload(conversation_message_participants, :user) participants = conversation_message_participants.map(&:user) subscribed & participants @@ -205,7 +205,7 @@ def new_recipients # for developer use on console only def resend_message! @re_send_message = true - self.save! + save! @re_send_message = false end @@ -285,14 +285,14 @@ def root_account_id end def reply_from(opts) - raise IncomingMail::Errors::UnknownAddress if self.context.try(:root_account).try(:deleted?) + raise IncomingMail::Errors::UnknownAddress if context.try(:root_account).try(:deleted?) # It would be nice to have group conversations via e-mail, but if so, we need to make it much more obvious # that replies to the e-mail will be sent to multiple recipients. recipients = [author] tags = conversation.conversation_participants.where(user_id: author.id).pluck(:tags) opts = opts.merge( - :root_account_id => self.root_account_id, + :root_account_id => root_account_id, :only_users => recipients, :tags => tags ) @@ -325,21 +325,21 @@ def to_atom(opts = {}) extend ApplicationHelper extend ConversationsHelper - title = ERB::Util.h(CanvasTextHelper.truncate_text(self.body, :max_words => 8, :max_length => 80)) + title = ERB::Util.h(CanvasTextHelper.truncate_text(body, :max_words => 8, :max_length => 80)) # build content, should be: # message body # [list of attachments] # ----- # context - content = "
#{ERB::Util.h(self.body)}
" - unless self.attachments.empty? + content = "
#{ERB::Util.h(body)}
" + unless attachments.empty? content += "
    " - self.attachments.each do |attachment| + attachments.each do |attachment| href = file_download_url(attachment, :verifier => attachment.uuid, :download => '1', :download_frd => '1', - :host => HostUrl.context_host(self.context)) + :host => HostUrl.context_host(context)) content += "
  • #{ERB::Util.h(attachment.display_name)}
  • " end content += "
" @@ -349,18 +349,18 @@ def to_atom(opts = {}) Atom::Entry.new do |entry| entry.title = title - entry.authors << Atom::Person.new(:name => self.author.name) - entry.updated = self.created_at.utc - entry.published = self.created_at.utc - entry.id = "tag:#{HostUrl.context_host(self.context)},#{self.created_at.strftime("%Y-%m-%d")}:/conversations/#{self.feed_code}" + entry.authors << Atom::Person.new(:name => author.name) + entry.updated = created_at.utc + entry.published = created_at.utc + entry.id = "tag:#{HostUrl.context_host(context)},#{created_at.strftime("%Y-%m-%d")}:/conversations/#{feed_code}" entry.links << Atom::Link.new(:rel => 'alternate', - :href => "http://#{HostUrl.context_host(self.context)}/conversations/#{self.conversation.id}") - self.attachments.each do |attachment| + :href => "http://#{HostUrl.context_host(context)}/conversations/#{conversation.id}") + attachments.each do |attachment| entry.links << Atom::Link.new(:rel => 'enclosure', :href => file_download_url(attachment, :verifier => attachment.uuid, :download => '1', :download_frd => '1', - :host => HostUrl.context_host(self.context))) + :host => HostUrl.context_host(context))) end entry.content = Atom::Content::Html.new(content) end diff --git a/app/models/conversation_message_participant.rb b/app/models/conversation_message_participant.rb index 2454863327394..5c4a403a04221 100644 --- a/app/models/conversation_message_participant.rb +++ b/app/models/conversation_message_participant.rb @@ -49,7 +49,7 @@ class ConversationMessageParticipant < ActiveRecord::Base delegate :conversation, to: :conversation_message def self.query_deleted(user_id, options = {}) - query = self.deleted.eager_load(:conversation_message).where(user_id: user_id).order(deleted_at: :desc) + query = deleted.eager_load(:conversation_message).where(user_id: user_id).order(deleted_at: :desc) query = query.where(conversation_messages: { conversation_id: options['conversation_id'] }) if options['conversation_id'] query = query.where('conversation_message_participants.deleted_at < ?', options['deleted_before']) if options['deleted_before'] diff --git a/app/models/conversation_participant.rb b/app/models/conversation_participant.rb index 3b2cc840d33a4..282d8b47d5a45 100644 --- a/app/models/conversation_participant.rb +++ b/app/models/conversation_participant.rb @@ -201,7 +201,7 @@ class ConversationParticipant < ActiveRecord::Base def as_json(options = {}) latest = last_message latest_authored = last_authored_message - subject = self.conversation.subject + subject = conversation.subject options[:include_context_info] ||= private? { :id => conversation_id, @@ -220,11 +220,11 @@ def as_json(options = {}) end def all_messages - self.conversation.shard.activate do - ConversationMessage.shard(self.conversation.shard) + conversation.shard.activate do + ConversationMessage.shard(conversation.shard) .select("conversation_messages.*, conversation_message_participants.tags") .joins(:conversation_message_participants) - .where("conversation_id=? AND user_id=?", self.conversation_id, self.user_id) + .where("conversation_id=? AND user_id=?", conversation_id, user_id) .order("created_at DESC, id DESC") end end @@ -285,19 +285,19 @@ def add_message(body_or_obj, options = {}) end def process_new_message(message_args, recipients, included_message_ids, tags) - if recipients && !self.private? - self.add_participants recipients, no_messages: true + if recipients && !private? + add_participants recipients, no_messages: true end - self.reload + reload if included_message_ids ConversationMessage.where(:id => included_message_ids).each do |msg| - self.conversation.add_message_to_participants(msg, new_message: false, only_users: recipients, reset_unread_counts: false) + conversation.add_message_to_participants(msg, new_message: false, only_users: recipients, reset_unread_counts: false) end end message = Conversation.build_message(*message_args) - self.add_message(message, :tags => tags, :update_for_sender => false, :only_users => recipients) + add_message(message, :tags => tags, :update_for_sender => false, :only_users => recipients) message end @@ -342,10 +342,10 @@ def delete_messages(*to_delete) # # Returns nothing. def remove_or_delete_messages(operation, *to_delete) - self.conversation.shard.activate do + conversation.shard.activate do scope = ConversationMessageParticipant.joins(:conversation_message) - .where(:conversation_messages => { :conversation_id => self.conversation_id }, - :user_id => self.user_id) + .where(:conversation_messages => { :conversation_id => conversation_id }, + :user_id => user_id) if to_delete == [:all] if operation == :delete scope.delete_all @@ -368,7 +368,7 @@ def remove_or_delete_messages(operation, *to_delete) save end # update the stream item data but leave the instances alone - StreamItem.delay_if_production(priority: 25).generate_or_update(self.conversation) + StreamItem.delay_if_production(priority: 25).generate_or_update(conversation) end def update(hash) @@ -414,7 +414,7 @@ def one_on_one? end def other_participants(participants = conversation.participants) - participants.reject { |u| u.id == self.user_id } + participants.reject { |u| u.id == user_id } end def other_participant @@ -492,7 +492,7 @@ def infer_tags def move_to_user(new_user) conversation.shard.activate do self.class.unscoped do - old_shard = self.user.shard + old_shard = user.shard conversation.conversation_messages.where(:author_id => user_id).update_all(:author_id => new_user.id) if (existing = conversation.conversation_participants.where(user_id: new_user).first) existing.update_attribute(:workflow_state, workflow_state) if unread? || existing.archived? @@ -500,7 +500,7 @@ def move_to_user(new_user) destroy else ConversationMessageParticipant.joins(:conversation_message) - .where(:conversation_messages => { :conversation_id => self.conversation_id }, :user_id => self.user_id) + .where(:conversation_messages => { :conversation_id => conversation_id }, :user_id => user_id) .update_all(:user_id => new_user.id) update_attribute :user, new_user clear_participants_cache @@ -528,7 +528,7 @@ def last_message attr_writer :last_authored_message def last_authored_message - @last_authored_message ||= self.conversation.shard.activate { messages.human.by_user(user_id).first } if visible_last_authored_at + @last_authored_message ||= conversation.shard.activate { messages.human.by_user(user_id).first } if visible_last_authored_at end def self.preload_latest_messages(conversations, author) @@ -572,10 +572,10 @@ def update_one(update_params) self.starred = false when 'destroy' - self.remove_messages(:all) + remove_messages(:all) end - self.save! + save! end def self.do_batch_update(progress, user, conversation_ids, update_params) @@ -616,7 +616,7 @@ def message_tags def destroy_conversation_message_participants @destroyed = true - delete_messages(:all) if self.conversation_id + delete_messages(:all) if conversation_id end def update_unread_count(direction = :up, user_id = self.user_id) diff --git a/app/models/course.rb b/app/models/course.rb index e1d3f335d5d19..7acfd77dfaeb8 100644 --- a/app/models/course.rb +++ b/app/models/course.rb @@ -40,7 +40,7 @@ def time_zone if read_attribute(:time_zone) super else - RequestCache.cache("account_time_zone", self.root_account_id) do + RequestCache.cache("account_time_zone", root_account_id) do root_account.default_time_zone end end @@ -175,7 +175,7 @@ def time_zone has_many :assessment_question_banks, -> { preload(:assessment_questions, :assessment_question_bank_users) }, as: :context, inverse_of: :context has_many :assessment_questions, :through => :assessment_question_banks def inherited_assessment_question_banks(include_self = false) - self.account.inherited_assessment_question_banks(true, *(include_self ? [self] : [])) + account.inherited_assessment_question_banks(true, *(include_self ? [self] : [])) end has_many :external_feeds, :as => :context, :inverse_of => :context, :dependent => :destroy @@ -318,7 +318,7 @@ def inherited_assessment_question_banks(include_self = false) MODERATED_GRADING_GRADER_LIMIT = 10 def [](attr) - attr.to_s == 'asset_string' ? self.asset_string : super + attr.to_s == 'asset_string' ? asset_string : super end def events_for(user) @@ -359,7 +359,7 @@ def self.skip_updating_account_associations? end def update_account_associations_if_changed - if (self.saved_change_to_root_account_id? || self.saved_change_to_account_id?) && !self.class.skip_updating_account_associations? + if (saved_change_to_root_account_id? || saved_change_to_account_id?) && !self.class.skip_updating_account_associations? delay(synchronous: !Rails.env.production? || saved_change_to_id?).update_account_associations end end @@ -368,12 +368,12 @@ def update_enrollment_states_if_necessary return if saved_change_to_id # new object, nothing to possibly invalidate if (saved_changes.keys & %w[restrict_enrollments_to_course_dates account_id enrollment_term_id]).any? || - (self.restrict_enrollments_to_course_dates? && (saved_changes.keys & %w[start_at conclude_at]).any?) || - (self.saved_change_to_workflow_state? && (completed? || self.workflow_state_before_last_save == 'completed')) + (restrict_enrollments_to_course_dates? && (saved_changes.keys & %w[start_at conclude_at]).any?) || + (saved_change_to_workflow_state? && (completed? || workflow_state_before_last_save == 'completed')) # a lot of things can change the date logic here :/ - if self.enrollments.exists? - EnrollmentState.delay_if_production(n_strand: ["invalidate_enrollment_states", self.global_root_account_id]) + if enrollments.exists? + EnrollmentState.delay_if_production(n_strand: ["invalidate_enrollment_states", global_root_account_id]) .invalidate_states_for_course_or_section(self) end # if the course date settings have been changed, we'll end up reprocessing all the access values anyway, so no need to queue below for other setting changes @@ -391,18 +391,18 @@ def update_enrollment_states_if_necessary def module_based? Rails.cache.fetch(['module_based_course', self].cache_key) do - self.context_modules.active.except(:order).any? { |m| m.completion_requirements && !m.completion_requirements.empty? } + context_modules.active.except(:order).any? { |m| m.completion_requirements && !m.completion_requirements.empty? } end end def has_modules? Rails.cache.fetch(['course_has_modules', self].cache_key) do - self.context_modules.not_deleted.any? + context_modules.not_deleted.any? end end def modules_visible_to(user, array_is_okay: false) - if self.grants_right?(user, :view_unpublished_items) + if grants_right?(user, :view_unpublished_items) if array_is_okay && association(:context_modules).loaded? context_modules.reject(&:deleted?) else @@ -418,10 +418,10 @@ def modules_visible_to(user, array_is_okay: false) end def module_items_visible_to(user) - tags = if (user_is_teacher = self.grants_right?(user, :view_unpublished_items)) - self.context_module_tags.not_deleted.joins(:context_module).where("context_modules.workflow_state <> 'deleted'") + tags = if (user_is_teacher = grants_right?(user, :view_unpublished_items)) + context_module_tags.not_deleted.joins(:context_module).where("context_modules.workflow_state <> 'deleted'") else - self.context_module_tags.active.joins(:context_module).where(:context_modules => { :workflow_state => 'active' }) + context_module_tags.active.joins(:context_module).where(:context_modules => { :workflow_state => 'active' }) end DifferentiableAssignment.scope_filter(tags, user, self, is_teacher: user_is_teacher) @@ -430,36 +430,36 @@ def module_items_visible_to(user) def sequential_module_item_ids Rails.cache.fetch(['ordered_module_item_ids', self].cache_key) do GuardRail.activate(:secondary) do - self.context_module_tags.not_deleted.joins(:context_module) - .where("context_modules.workflow_state <> 'deleted'") - .where("content_tags.content_type <> 'ContextModuleSubHeader'") - .reorder(Arel.sql("COALESCE(context_modules.position, 0), context_modules.id, content_tags.position NULLS LAST")) - .pluck(:id) + context_module_tags.not_deleted.joins(:context_module) + .where("context_modules.workflow_state <> 'deleted'") + .where("content_tags.content_type <> 'ContextModuleSubHeader'") + .reorder(Arel.sql("COALESCE(context_modules.position, 0), context_modules.id, content_tags.position NULLS LAST")) + .pluck(:id) end end end def verify_unique_ids - infer_root_account unless self.root_account_id + infer_root_account unless root_account_id is_unique = true - if self.sis_source_id && (root_account_id_changed? || sis_source_id_changed?) - scope = root_account.all_courses.where(sis_source_id: self.sis_source_id) - scope = scope.where("id<>?", self) unless self.new_record? + if sis_source_id && (root_account_id_changed? || sis_source_id_changed?) + scope = root_account.all_courses.where(sis_source_id: sis_source_id) + scope = scope.where("id<>?", self) unless new_record? if scope.exists? is_unique = false - self.errors.add(:sis_source_id, t('errors.sis_in_use', "SIS ID \"%{sis_id}\" is already in use", - :sis_id => self.sis_source_id)) + errors.add(:sis_source_id, t('errors.sis_in_use', "SIS ID \"%{sis_id}\" is already in use", + :sis_id => sis_source_id)) end end - if self.integration_id && (root_account_id_changed? || integration_id_changed?) - scope = root_account.all_courses.where(integration_id: self.integration_id) - scope = scope.where("id<>?", self) unless self.new_record? + if integration_id && (root_account_id_changed? || integration_id_changed?) + scope = root_account.all_courses.where(integration_id: integration_id) + scope = scope.where("id<>?", self) unless new_record? if scope.exists? is_unique = false - self.errors.add(:integration_id, t("Integration ID \"%{int_id}\" is already in use", - :int_id => self.integration_id)) + errors.add(:integration_id, t("Integration ID \"%{int_id}\" is already in use", + :int_id => integration_id)) end end @@ -468,7 +468,7 @@ def verify_unique_ids def validate_course_dates if start_at.present? && conclude_at.present? && conclude_at < start_at - self.errors.add(:conclude_at, t("End date cannot be before start date")) + errors.add(:conclude_at, t("End date cannot be before start date")) false else true @@ -476,34 +476,34 @@ def validate_course_dates end def validate_banner_image - if self.banner_image_url.present? && self.banner_image_id.present? - self.errors.add(:banner_image, t("banner_image_url and banner_image_id cannot both be set.")) + if banner_image_url.present? && banner_image_id.present? + errors.add(:banner_image, t("banner_image_url and banner_image_id cannot both be set.")) false - elsif (self.banner_image_id.present? && valid_course_image_id?(self.banner_image_id)) || - (self.banner_image_url.present? && valid_course_image_url?(self.banner_image_url)) + elsif (banner_image_id.present? && valid_course_image_id?(banner_image_id)) || + (banner_image_url.present? && valid_course_image_url?(banner_image_url)) true else - if self.banner_image_id.present? - self.errors.add(:banner_image_id, t("banner_image_id is not a valid ID")) - elsif self.banner_image_url.present? - self.errors.add(:banner_image_url, t("banner_image_url is not a valid URL")) + if banner_image_id.present? + errors.add(:banner_image_id, t("banner_image_id is not a valid ID")) + elsif banner_image_url.present? + errors.add(:banner_image_url, t("banner_image_url is not a valid URL")) end false end end def validate_course_image - if self.image_url.present? && self.image_id.present? - self.errors.add(:image, t("image_url and image_id cannot both be set.")) + if image_url.present? && image_id.present? + errors.add(:image, t("image_url and image_id cannot both be set.")) false - elsif (self.image_id.present? && valid_course_image_id?(self.image_id)) || - (self.image_url.present? && valid_course_image_url?(self.image_url)) + elsif (image_id.present? && valid_course_image_id?(image_id)) || + (image_url.present? && valid_course_image_url?(image_url)) true else - if self.image_id.present? - self.errors.add(:image_id, t("image_id is not a valid ID")) - elsif self.image_url.present? - self.errors.add(:image_url, t("image_url is not a valid URL")) + if image_id.present? + errors.add(:image_id, t("image_id is not a valid ID")) + elsif image_url.present? + errors.add(:image_url, t("image_url is not a valid URL")) end false end @@ -518,12 +518,12 @@ def valid_course_image_url?(image_url) end def validate_default_view - if self.default_view_changed? - if !%w[assignments feed modules syllabus wiki].include?(self.default_view) - self.errors.add(:default_view, t("Home page is not valid")) + if default_view_changed? + if !%w[assignments feed modules syllabus wiki].include?(default_view) + errors.add(:default_view, t("Home page is not valid")) return false - elsif self.default_view == 'wiki' && !(self.wiki_id && self.wiki.has_front_page?) - self.errors.add(:default_view, t("A Front Page is required")) + elsif default_view == 'wiki' && !(wiki_id && wiki.has_front_page?) + errors.add(:default_view, t("A Front Page is required")) return false end end @@ -543,27 +543,27 @@ def validate_template def validate_not_on_siteadmin if root_account_id_changed? && root_account_id == Account.site_admin&.id - self.errors.add(:root_account_id, t("Courses cannot be created on the site_admin account.")) + errors.add(:root_account_id, t("Courses cannot be created on the site_admin account.")) end end def image - @image ||= if self.image_id.present? - self.shard.activate do - self.attachments.active.where(id: self.image_id).take&.public_download_url(1.week) + @image ||= if image_id.present? + shard.activate do + attachments.active.where(id: image_id).take&.public_download_url(1.week) end - elsif self.image_url - self.image_url + elsif image_url + image_url end end def banner_image - @banner_image ||= if self.banner_image_id.present? - self.shard.activate do - self.attachments.active.where(id: self.banner_image_id).take&.public_download_url(1.week) + @banner_image ||= if banner_image_id.present? + shard.activate do + attachments.active.where(id: banner_image_id).take&.public_download_url(1.week) end - elsif self.banner_image_url - self.banner_image_url + elsif banner_image_url + banner_image_url end end @@ -582,7 +582,7 @@ def course_visibility_options :setting => t('public', 'Public') } ] - options = self.root_account.available_course_visibility_override_options(options).to_a.flatten + options = root_account.available_course_visibility_override_options(options).to_a.flatten ActiveSupport::OrderedHash[*options] end @@ -618,8 +618,8 @@ def syllabus_visibility_option end def course_visibility - if self.overridden_course_visibility.present? - self.overridden_course_visibility + if overridden_course_visibility.present? + overridden_course_visibility elsif is_public == true 'public' elsif is_public_to_auth_users == true @@ -647,8 +647,8 @@ def readable_license end def unpublishable? - ids = self.all_real_students.pluck :id - !self.submissions.with_assignment.with_point_data.where(:user_id => ids).exists? + ids = all_real_students.pluck :id + !submissions.with_assignment.with_point_data.where(:user_id => ids).exists? end def self.update_account_associations(courses_or_course_ids, opts = {}) @@ -758,7 +758,7 @@ def self.update_account_associations(courses_or_course_ids, opts = {}) end def update_account_associations - self.shard.activate do + shard.activate do Course.update_account_associations([self]) end end @@ -783,8 +783,8 @@ def associated_accounts SQL end end - accounts << self.account if account_id && !accounts.find { |a| a.id == account_id } - accounts << self.root_account if root_account_id && !accounts.find { |a| a.id == root_account_id } + accounts << account if account_id && !accounts.find { |a| a.id == account_id } + accounts << root_account if root_account_id && !accounts.find { |a| a.id == root_account_id } accounts end end @@ -913,7 +913,7 @@ def broadcast_data p.data { broadcast_data } p.dispatch :new_course - p.to { self.root_account.account_users.active } + p.to { root_account.account_users.active } p.whenever { |record| record.root_account && ((record.just_created && record.name != Course.default_name) || @@ -945,7 +945,7 @@ def instructors_in_charge_of(user_id, require_grade_permissions: true) .where.not(course_section_id: nil) section_ids = scope.distinct.pluck(:course_section_id) - instructor_enrollment_scope = self.instructor_enrollments.active_by_date + instructor_enrollment_scope = instructor_enrollments.active_by_date if section_ids.any? instructor_enrollment_scope = instructor_enrollment_scope.where("enrollments.limit_privileges_to_course_section IS NULL OR enrollments.limit_privileges_to_course_section<>? OR enrollments.course_section_id IN (?)", true, section_ids) @@ -977,7 +977,7 @@ def user_is_admin?(user) return unless user fetch_on_enrollments('user_is_admin', user) do - self.enrollments.for_user(user).active.of_admin_type.exists? + enrollments.for_user(user).active.of_admin_type.exists? end end @@ -985,7 +985,7 @@ def user_is_instructor?(user) return unless user fetch_on_enrollments('user_is_instructor', user) do - self.enrollments.for_user(user).active_by_date.of_instructor_type.exists? + enrollments.for_user(user).active_by_date.of_instructor_type.exists? end end @@ -996,13 +996,13 @@ def user_is_student?(user, opts = {}) enroll_types = ["StudentEnrollment"] enroll_types << "StudentViewEnrollment" if opts[:include_fake_student] - enroll_scope = self.enrollments.for_user(user).where(:type => enroll_types) + enroll_scope = enrollments.for_user(user).where(:type => enroll_types) if opts[:include_future] enroll_scope = enroll_scope.active_or_pending_by_date_ignoring_access elsif opts[:include_all] enroll_scope = enroll_scope.not_inactive_by_date_ignoring_access else - return false unless self.available? + return false unless available? enroll_scope = enroll_scope.active_by_date end @@ -1012,9 +1012,9 @@ def user_is_student?(user, opts = {}) def preload_user_roles! # plz to use before you make a billion calls to user_has_been_X? with different users - @user_ids_by_enroll_type ||= self.shard.activate do + @user_ids_by_enroll_type ||= shard.activate do map = {} - self.enrollments.active.pluck(:user_id, :type).each do |user_id, type| + enrollments.active.pluck(:user_id, :type).each do |user_id, type| map[type] ||= [] map[type] << user_id end @@ -1023,7 +1023,7 @@ def preload_user_roles! end def preloaded_user_has_been?(user, types) - self.shard.activate do + shard.activate do Array(types).any? { |type| @user_ids_by_enroll_type.key?(type) && @user_ids_by_enroll_type[type].include?(user.id) } end end @@ -1036,7 +1036,7 @@ def user_has_been_instructor?(user) # enrollments should be on the course's shard fetch_on_enrollments('user_has_been_instructor', user) do - self.instructor_enrollments.active.where(user_id: user).exists? # active here is !deleted; it still includes concluded, etc. + instructor_enrollments.active.where(user_id: user).exists? # active here is !deleted; it still includes concluded, etc. end end @@ -1047,7 +1047,7 @@ def user_has_been_admin?(user) end fetch_on_enrollments('user_has_been_admin', user) do - self.admin_enrollments.active.where(user_id: user).exists? # active here is !deleted; it still includes concluded, etc. + admin_enrollments.active.where(user_id: user).exists? # active here is !deleted; it still includes concluded, etc. end end @@ -1058,7 +1058,7 @@ def user_has_been_observer?(user) end fetch_on_enrollments('user_has_been_observer', user) do - self.observer_enrollments.shard(self).active.where(user_id: user).exists? # active here is !deleted; it still includes concluded, etc. + observer_enrollments.shard(self).active.where(user_id: user).exists? # active here is !deleted; it still includes concluded, etc. end end @@ -1069,7 +1069,7 @@ def user_has_been_student?(user) end fetch_on_enrollments('user_has_been_student', user) do - self.all_student_enrollments.where(user_id: user).exists? + all_student_enrollments.where(user_id: user).exists? end end @@ -1077,7 +1077,7 @@ def user_has_no_enrollments?(user) return unless user if @user_ids_by_enroll_type - self.shard.activate do + shard.activate do return @user_ids_by_enroll_type.values.none? { |arr| arr.include?(user.id) } end end @@ -1104,12 +1104,12 @@ def apply_assignment_group_weights=(apply) def grade_weight_changed! @grade_weight_changed = true - self.save! + save! @grade_weight_changed = false end def membership_for_user(user) - self.enrollments.where(user_id: user).order(:workflow_state).first if user + enrollments.where(user_id: user).order(:workflow_state).first if user end def infer_root_account @@ -1118,22 +1118,22 @@ def infer_root_account end def assert_defaults - self.name = nil if self.name&.strip&.empty? + self.name = nil if name&.strip&.empty? self.name ||= t('missing_name', "Unnamed Course") self.name.delete!("\r") - self.course_code = nil if self.course_code == '' - if !self.course_code && self.name + self.course_code = nil if course_code == '' + if !course_code && self.name res = [] split = self.name.split(/\s/) res << split[0] res << split[1..].find { |txt| txt.match(/\d/) } rescue nil self.course_code = res.compact.join(" ") end - @group_weighting_scheme_changed = self.group_weighting_scheme_changed? - if self.account_id && self.account_id_changed? + @group_weighting_scheme_changed = group_weighting_scheme_changed? + if account_id && account_id_changed? infer_root_account end - if self.root_account_id && self.root_account_id_changed? + if self.root_account_id && root_account_id_changed? if account if account.root_account? self.account = nil if root_account_id != account.id @@ -1145,10 +1145,10 @@ def assert_defaults end self.root_account = Account.default if root_account_id.nil? self.account_id ||= self.root_account_id - self.enrollment_term = nil if self.enrollment_term.try(:root_account_id) != self.root_account_id - self.enrollment_term ||= self.root_account.default_enrollment_term - self.allow_student_wiki_edits = (self.default_wiki_editing_roles || "").split(',').include?('students') - if self.course_format && !['on_campus', 'online', 'blended'].include?(self.course_format) + self.enrollment_term = nil if enrollment_term.try(:root_account_id) != self.root_account_id + self.enrollment_term ||= root_account.default_enrollment_term + self.allow_student_wiki_edits = (default_wiki_editing_roles || "").split(',').include?('students') + if course_format && !['on_campus', 'online', 'blended'].include?(course_format) self.course_format = nil end self.default_view ||= default_home_page @@ -1156,14 +1156,14 @@ def assert_defaults end def update_enrollments_later - self.update_enrolled_users if !self.new_record? && !(self.changes.keys & ['workflow_state', 'name', 'course_code', 'start_at', 'conclude_at', 'enrollment_term_id']).empty? + update_enrolled_users if !new_record? && !(changes.keys & ['workflow_state', 'name', 'course_code', 'start_at', 'conclude_at', 'enrollment_term_id']).empty? true end def update_enrolled_users(sis_batch: nil) - self.shard.activate do - if self.workflow_state_changed? || (sis_batch && self.saved_change_to_workflow_state?) - if self.completed? + shard.activate do + if workflow_state_changed? || (sis_batch && saved_change_to_workflow_state?) + if completed? enrollment_info = Enrollment.where(:course_id => self, :workflow_state => ['active', 'invited']).select(:id, :workflow_state).to_a if enrollment_info.any? data = SisBatchRollBackData.build_dependent_data(sis_batch: sis_batch, contexts: enrollment_info, updated_state: 'completed') @@ -1179,7 +1179,7 @@ def update_enrolled_users(sis_batch: nil) appointment_participants.active.current.update_all(:workflow_state => 'deleted') appointment_groups.each(&:clear_cached_available_slots!) - elsif self.deleted? + elsif deleted? enroll_scope = Enrollment.where("course_id=? AND workflow_state<>'deleted'", self) user_ids = enroll_scope.group(:user_id).pluck(:user_id).uniq @@ -1199,7 +1199,7 @@ def update_enrolled_users(sis_batch: nil) end end - if self.root_account_id_changed? + if root_account_id_changed? CourseSection.where(:course_id => self).update_all(:root_account_id => self.root_account_id) Enrollment.where(:course_id => self).update_all(:root_account_id => self.root_account_id) end @@ -1215,11 +1215,11 @@ def update_enrolled_users(sis_batch: nil) end def self_enrollment_allowed? - !!(self.account && self.account.self_enrollment_allowed?(self)) + !!(account && account.self_enrollment_allowed?(self)) end def self_enrollment_enabled? - self.self_enrollment? && self.self_enrollment_allowed? + self_enrollment? && self_enrollment_allowed? end def self_enrollment_code @@ -1265,7 +1265,7 @@ def self_enrollment_codes end def update_show_total_grade_as_on_weighting_scheme_change - if group_weighting_scheme_changed? && self.group_weighting_scheme == 'percent' + if group_weighting_scheme_changed? && group_weighting_scheme == 'percent' self.show_total_grade_as_points = false end true @@ -1274,7 +1274,7 @@ def update_show_total_grade_as_on_weighting_scheme_change # set license to "private" if it's present but not recognized def validate_license unless license.nil? - self.license = 'private' unless self.class.licenses.key?(self.license) + self.license = 'private' unless self.class.licenses.key?(license) end end @@ -1293,7 +1293,7 @@ def update_cached_due_dates def update_final_scores_on_weighting_scheme_change if @group_weighting_scheme_changed - self.class.connection.after_transaction_commit { self.recompute_student_scores } + self.class.connection.after_transaction_commit { recompute_student_scores } end end @@ -1340,21 +1340,21 @@ def recompute_student_scores_without_send_later(student_ids = nil, opts = {}) Rails.logger.debug "GRADES: recomputing scores in course=#{global_id} students=#{visible_student_ids.inspect}" Enrollment.recompute_final_score( visible_student_ids, - self.id, + id, grading_period_id: opts[:grading_period_id], update_all_grading_period_scores: opts.fetch(:update_all_grading_period_scores, true) ) end def handle_syllabus_changes_for_master_migration - if self.syllabus_body_changed? + if syllabus_body_changed? self.syllabus_updated_at = Time.now.utc if @master_migration updating_master_template_id = @master_migration.master_course_subscription.master_template_id # master migration sync - self.syllabus_master_template_id ||= updating_master_template_id if self.syllabus_body_was.blank? # sync if there was no syllabus before + self.syllabus_master_template_id ||= updating_master_template_id if syllabus_body_was.blank? # sync if there was no syllabus before if self.syllabus_master_template_id.to_i != updating_master_template_id - self.restore_syllabus_body! # revert the change + restore_syllabus_body! # revert the change @master_migration.add_skipped_item(:syllabus) end elsif self.syllabus_master_template_id @@ -1365,7 +1365,7 @@ def handle_syllabus_changes_for_master_migration end def home_page - self.wiki.front_page + wiki.front_page end def context_code @@ -1420,7 +1420,7 @@ def do_claim end def invite_uninvited_students - self.enrollments.where(workflow_state: "creation_pending").each(&:invite!) + enrollments.where(workflow_state: "creation_pending").each(&:invite!) end workflow do @@ -1497,12 +1497,12 @@ def self.destroy_batch(courses, sis_batch: nil, batch_mode: false) end def call_event(event) - self.send(event) if self.current_state.events.include? event.to_sym + send(event) if current_state.events.include? event.to_sym end def claim_with_teacher(user) raise "Must provide a valid teacher" unless user - return unless self.state == :created + return unless state == :created e = enroll_user(user, 'TeacherEnrollment', :enrollment_state => 'active') # teacher(user) claim @@ -1523,12 +1523,12 @@ def self.require_assignment_groups(contexts) def require_assignment_group shard.activate do - key = ['has_assignment_group', self.global_id].cache_key + key = ['has_assignment_group', global_id].cache_key return if Rails.cache.read(key) - if self.assignment_groups.active.empty? + if assignment_groups.active.empty? GuardRail.activate(:primary) do - self.assignment_groups.create!(name: t('#assignment_group.default_name', "Assignments")) + assignment_groups.create!(name: t('#assignment_group.default_name', "Assignments")) end end Rails.cache.write(key, true) @@ -1539,7 +1539,7 @@ def self.create_unique(uuid = nil, account_id = nil, root_account_id = nil) uuid ||= CanvasSlug.generate_securish_uuid course = where(uuid: uuid).first_or_initialize course = Course.new if course.deleted? - course.name = self.default_name if course.new_record? + course.name = default_name if course.new_record? course.short_name = t('default_short_name', "Course-101") if course.new_record? course.account_id = account_id || root_account_id course.root_account_id = root_account_id @@ -1548,7 +1548,7 @@ def self.create_unique(uuid = nil, account_id = nil, root_account_id = nil) end def <=>(other) - self.id <=> other.id + id <=> other.id end def quota @@ -1571,7 +1571,7 @@ def storage_quota_used_mb def storage_quota read_attribute(:storage_quota) || - (self.account.default_storage_quota rescue nil) || + (account.default_storage_quota rescue nil) || Setting.get('course_default_quota', 500.megabytes.to_s).to_i end @@ -1596,36 +1596,36 @@ def full_name def to_atom Atom::Entry.new do |entry| entry.title = self.name - entry.updated = self.updated_at - entry.published = self.created_at + entry.updated = updated_at + entry.published = created_at entry.links << Atom::Link.new(:rel => 'alternate', - :href => "/#{context_url_prefix}/courses/#{self.id}") + :href => "/#{context_url_prefix}/courses/#{id}") end end def unenrolled_user_can_read?(_user, session) - self.is_public || (self.is_public_to_auth_users && session.present? && session.key?(:user_id)) + is_public || (is_public_to_auth_users && session.present? && session.key?(:user_id)) end set_policy do - given { |user, session| self.available? && unenrolled_user_can_read?(user, session) } + given { |user, session| available? && unenrolled_user_can_read?(user, session) } can :read and can :read_outcomes and can :read_syllabus - given { |_user, session| self.available? && (self.public_syllabus || (self.public_syllabus_to_auth && session.present? && session.key?(:user_id))) } + given { |_user, session| available? && (public_syllabus || (public_syllabus_to_auth && session.present? && session.key?(:user_id))) } can :read_syllabus RoleOverride.permissions.each do |permission, details| given do |user| - self.active_enrollment_allows(user, permission, !details[:restrict_future_enrollments]) || - self.account_membership_allows(user, permission) + active_enrollment_allows(user, permission, !details[:restrict_future_enrollments]) || + account_membership_allows(user, permission) end can permission end - given { |_user, session| session && session[:enrollment_uuid] && (hash = Enrollment.course_user_state(self, session[:enrollment_uuid]) || {}) && (hash[:enrollment_state] == "invited" || (hash[:enrollment_state] == "active" && hash[:user_state].to_s == "pre_registered")) && (self.available? || self.completed? || (self.claimed? && hash[:is_admin])) } + given { |_user, session| session && session[:enrollment_uuid] && (hash = Enrollment.course_user_state(self, session[:enrollment_uuid]) || {}) && (hash[:enrollment_state] == "invited" || (hash[:enrollment_state] == "active" && hash[:user_state].to_s == "pre_registered")) && (available? || completed? || (claimed? && hash[:is_admin])) } can :read and can :read_outcomes - given { |user| (self.available? || self.completed?) && user && fetch_on_enrollments("has_not_inactive_enrollment", user) { enrollments.for_user(user).not_inactive_by_date.exists? } } + given { |user| (available? || completed?) && user && fetch_on_enrollments("has_not_inactive_enrollment", user) { enrollments.for_user(user).not_inactive_by_date.exists? } } can :read and can :read_outcomes # Active students @@ -1635,7 +1635,7 @@ def unenrolled_user_can_read?(_user, session) can :read and can :participate_as_student and can :read_grades and can :read_outcomes given { |user| - (self.available? || self.completed?) && user && + (available? || completed?) && user && fetch_on_enrollments("has_active_observer_enrollment", user) { enrollments.for_user(user).active_by_date.where(:type => "ObserverEnrollment").where.not(:associated_user_id => nil).exists? } } can :read_grades @@ -1643,8 +1643,8 @@ def unenrolled_user_can_read?(_user, session) # Active admins (Teacher/TA/Designer) #################### Begin legacy permission block ######################### given do |user| - !self.root_account.feature_enabled?(:granular_permissions_manage_courses) && !self.deleted? && - !self.sis_source_id && user && !template? && + !root_account.feature_enabled?(:granular_permissions_manage_courses) && !deleted? && + !sis_source_id && user && !template? && fetch_on_enrollments('active_content_admin_enrollments', user) { enrollments.for_user(user).of_content_admins.active_by_date.to_a }.any? { |e| e.has_permission_to?(:change_course_state) } @@ -1652,7 +1652,7 @@ def unenrolled_user_can_read?(_user, session) can :delete given do |user| - !self.root_account.feature_enabled?(:granular_permissions_manage_courses) && !self.deleted? && + !root_account.feature_enabled?(:granular_permissions_manage_courses) && !deleted? && user && fetch_on_enrollments('has_active_content_admin_enrollment', user) do enrollments.for_user(user).of_content_admins.active_by_date.exists? end @@ -1661,7 +1661,7 @@ def unenrolled_user_can_read?(_user, session) ##################### End legacy permission block ########################## given do |user| - user && (self.available? || self.created? || self.claimed?) && + user && (available? || created? || claimed?) && fetch_on_enrollments('has_active_admin_enrollment', user) do enrollments.for_user(user).of_admin_type.active_by_date.exists? end @@ -1672,8 +1672,8 @@ def unenrolled_user_can_read?(_user, session) # Teachers and Designers can reset content, but not TAs given do |user| - self.root_account.feature_enabled?(:granular_permissions_manage_courses) && - user && !self.deleted? && !template? && + root_account.feature_enabled?(:granular_permissions_manage_courses) && + user && !deleted? && !template? && fetch_on_enrollments('active_content_admin_enrollments', user) { enrollments.for_user(user).of_content_admins.active_by_date.to_a }.any? { |e| e.has_permission_to?(:manage_courses_reset) } @@ -1682,8 +1682,8 @@ def unenrolled_user_can_read?(_user, session) # Teachers and Designers can delete, but not TAs given do |user| - self.root_account.feature_enabled?(:granular_permissions_manage_courses) && user && - !template? && !self.deleted? && !self.sis_source_id && + root_account.feature_enabled?(:granular_permissions_manage_courses) && user && + !template? && !deleted? && !sis_source_id && fetch_on_enrollments('active_content_admin_enrollments', user) { enrollments.for_user(user).of_content_admins.active_by_date.to_a }.any? { |e| e.has_permission_to?(:manage_courses_delete) } @@ -1703,7 +1703,7 @@ def unenrolled_user_can_read?(_user, session) # Admin (Teacher/TA/Designer) of a concluded course given do |user| - !self.deleted? && user && + !deleted? && user && fetch_on_enrollments("has_completed_admin_enrollment", user) { enrollments.for_user(user).of_admin_type.completed_by_date.exists? } end can [:read, :read_as_admin, :use_student_view, :read_outcomes, :view_unpublished_items, :read_rubrics] @@ -1713,7 +1713,7 @@ def unenrolled_user_can_read?(_user, session) applicable_roles = details[:applies_to_concluded].is_a?(Array) && details[:applies_to_concluded] given do |user| - !self.deleted? && user && + !deleted? && user && fetch_on_enrollments("completed_enrollments", user) { enrollments.for_user(user).completed_by_date.to_a }.any? { |e| e.has_permission_to?(permission) && (!applicable_roles || applicable_roles.include?(e.type)) } end can permission @@ -1722,8 +1722,8 @@ def unenrolled_user_can_read?(_user, session) # Teacher or Designer of a concluded course #################### Begin legacy permission block ######################### given do |user| - !self.root_account.feature_enabled?(:granular_permissions_manage_courses) && !self.deleted? && - !self.sis_source_id && user && !template? && + !root_account.feature_enabled?(:granular_permissions_manage_courses) && !deleted? && + !sis_source_id && user && !template? && enrollments.for_user(user).of_content_admins.completed_by_date.to_a.any? do |e| e.has_permission_to?(:change_course_state) end @@ -1732,8 +1732,8 @@ def unenrolled_user_can_read?(_user, session) ##################### End legacy permission block ########################## given do |user| - self.root_account.feature_enabled?(:granular_permissions_manage_courses) && user && - !self.sis_source_id && !self.deleted? && !template? && + root_account.feature_enabled?(:granular_permissions_manage_courses) && user && + !sis_source_id && !deleted? && !template? && enrollments.for_user(user).of_content_admins.completed_by_date.to_a.any? do |e| e.has_permission_to?(:manage_courses_delete) end @@ -1742,7 +1742,7 @@ def unenrolled_user_can_read?(_user, session) # Student of a concluded course given do |user| - (self.available? || self.completed?) && user && + (available? || completed?) && user && fetch_on_enrollments("has_completed_student_enrollment", user) do enrollments.for_user(user).completed_by_date .where("enrollments.type = ? OR (enrollments.type = ? AND enrollments.associated_user_id IS NOT NULL)", "StudentEnrollment", "ObserverEnrollment").exists? @@ -1753,59 +1753,59 @@ def unenrolled_user_can_read?(_user, session) # Admin #################### Begin legacy permission block ######################### given do |user| - !self.root_account&.feature_enabled?(:granular_permissions_manage_courses) && - self.account_membership_allows(user, :manage_courses) + !root_account&.feature_enabled?(:granular_permissions_manage_courses) && + account_membership_allows(user, :manage_courses) end can :read_as_admin and can :manage and can :update and can :use_student_view and can :reset_content and can :view_unpublished_items and can :manage_feature_flags and can :view_feature_flags given do |user| - !self.root_account&.feature_enabled?(:granular_permissions_manage_courses) && !template? && - self.account_membership_allows(user, :manage_courses) && self.grants_right?(user, :change_course_state) + !root_account&.feature_enabled?(:granular_permissions_manage_courses) && !template? && + account_membership_allows(user, :manage_courses) && grants_right?(user, :change_course_state) end can :delete given do |user| - !self.root_account&.feature_enabled?(:granular_permissions_manage_courses) && !self.deleted? && - self.sis_source_id && self.account_membership_allows(user, :manage_sis) && !template? && - self.grants_right?(user, :change_course_state) + !root_account&.feature_enabled?(:granular_permissions_manage_courses) && !deleted? && + sis_source_id && account_membership_allows(user, :manage_sis) && !template? && + grants_right?(user, :change_course_state) end can :delete ##################### End legacy permission block ########################## - given { |user| self.account_membership_allows(user) } + given { |user| account_membership_allows(user) } can :read_as_admin and can :view_unpublished_items given do |user| - self.root_account.feature_enabled?(:granular_permissions_manage_courses) && - self.account_membership_allows(user, :manage_courses_admin) + root_account.feature_enabled?(:granular_permissions_manage_courses) && + account_membership_allows(user, :manage_courses_admin) end can :manage and can :update and can :use_student_view and can :manage_feature_flags and can :view_feature_flags # reset course content given do |user| - self.root_account.feature_enabled?(:granular_permissions_manage_courses) && !template? && - self.account_membership_allows(user, :manage_courses_reset) + root_account.feature_enabled?(:granular_permissions_manage_courses) && !template? && + account_membership_allows(user, :manage_courses_reset) end can :reset_content # delete or undelete a given course given do |user| - self.root_account.feature_enabled?(:granular_permissions_manage_courses) && !template? && - self.account_membership_allows(user, :manage_courses_delete) + root_account.feature_enabled?(:granular_permissions_manage_courses) && !template? && + account_membership_allows(user, :manage_courses_delete) end can :delete - given { |user| self.account_membership_allows(user, :read_course_content) } + given { |user| account_membership_allows(user, :read_course_content) } can :read and can :read_outcomes # Admins with read_roster can see prior enrollments (can't just check read_roster directly, # because students can't see prior enrollments) - given { |user| self.grants_all_rights?(user, :read_roster, :read_as_admin) } + given { |user| grants_all_rights?(user, :read_roster, :read_as_admin) } can :read_prior_roster - given { |user| self.grants_right?(user, :lti_add_edit) } + given { |user| grants_right?(user, :lti_add_edit) } can :create_tool_manually end @@ -1821,11 +1821,11 @@ def allows_speed_grader? end def active_enrollment_allows(user, permission, allow_future = true) - return false unless user && permission && !self.deleted? + return false unless user && permission && !deleted? - is_unpublished = self.created? || self.claimed? + is_unpublished = created? || claimed? active_enrollments = fetch_on_enrollments("active_enrollments_for_permissions2", user, is_unpublished) do - scope = self.enrollments.for_user(user).active_or_pending_by_date.select("enrollments.*, enrollment_states.state AS date_based_state_in_db") + scope = enrollments.for_user(user).active_or_pending_by_date.select("enrollments.*, enrollment_states.state AS date_based_state_in_db") scope = scope.where(:type => ['TeacherEnrollment', 'TaEnrollment', 'DesignerEnrollment', 'StudentViewEnrollment']) if is_unpublished scope.to_a.each(&:clear_association_cache) end @@ -1853,7 +1853,7 @@ def recently_ended? # People may conclude courses and then unclude them. This is a good alias_method # to check for in situations where we are dependent on those cases def inactive? - self.deleted? || self.completed? + deleted? || completed? end # Public: Return true if the end date for a course (or its term, if the course doesn't have one) has passed. @@ -1894,13 +1894,13 @@ def account_chain_ids end def institution_name - return self.root_account.name if self.root_account_id != Account.default.id + return root_account.name if self.root_account_id != Account.default.id - (self.account || self.root_account).name + (account || root_account).name end def account_users_for(user) - @associated_account_ids ||= (self.associated_accounts + root_account.account_chain(include_site_admin: true)) + @associated_account_ids ||= (associated_accounts + root_account.account_chain(include_site_admin: true)) .uniq.filter_map { |a| a.active? ? a.id : nil } Shard.partition_by_shard(@associated_account_ids) do |account_chain_ids| if account_chain_ids == [Account.site_admin.id] @@ -1927,7 +1927,7 @@ def account_membership_allows(user, permission = nil) return false unless user @membership_allows ||= {} - @membership_allows[[user.id, permission]] ||= self.cached_account_users_for(user).any? { |au| permission.nil? || au.has_permission_to?(self, permission) } + @membership_allows[[user.id, permission]] ||= cached_account_users_for(user).any? { |au| permission.nil? || au.has_permission_to?(self, permission) } end def grade_publishing_status_translation(status, message) @@ -2031,7 +2031,7 @@ def publish_final_grades(publishing_user, user_ids_to_publish = nil) settings = Canvas::Plugin.find!('grade_export').settings last_publish_attempt_at = Time.now.utc - scope = self.student_enrollments.not_fake + scope = student_enrollments.not_fake scope = scope.where(user_id: user_ids_to_publish) if user_ids_to_publish scope.update_all(:grade_publishing_status => "pending", :grade_publishing_message => nil, @@ -2046,8 +2046,8 @@ def send_final_grades_to_endpoint(publishing_user, user_ids_to_publish = nil) # actual grade publishing logic is here, but you probably want # 'publish_final_grades' - self.recompute_student_scores_without_send_later(user_ids_to_publish) - enrollments = self.student_enrollments.not_fake.eager_load(:user).preload(:course_section).order_by_sortable_name + recompute_student_scores_without_send_later(user_ids_to_publish) + enrollments = student_enrollments.not_fake.eager_load(:user).preload(:course_section).order_by_sortable_name enrollments = enrollments.where(user_id: user_ids_to_publish) if user_ids_to_publish errors = [] @@ -2063,7 +2063,7 @@ def send_final_grades_to_endpoint(publishing_user, user_ids_to_publish = nil) format_settings = Course.valid_grade_export_types[settings[:format_type]] raise "unknown format type: #{settings[:format_type]}" unless format_settings - raise "grade publishing requires a grading standard" if !self.grading_standard_enabled? && format_settings[:requires_grading_standard] + raise "grade publishing requires a grading standard" if !grading_standard_enabled? && format_settings[:requires_grading_standard] publishing_pseudonym = SisPseudonym.for(publishing_user, self) raise "publishing disallowed for this publishing user" if publishing_pseudonym.nil? && format_settings[:requires_publishing_pseudonym] @@ -2116,7 +2116,7 @@ def generate_grade_publishing_csv_output(enrollments, publishing_user, publishin "enrollment_status", "score" ] - column_names << "grade" if self.grading_standard_enabled? + column_names << "grade" if grading_standard_enabled? csv << column_names enrollments.each do |enrollment| @@ -2134,7 +2134,7 @@ def generate_grade_publishing_csv_output(enrollments, publishing_user, publishin end sis_pseudonyms = - SisPseudonym.for(enrollment.user, self.root_account, include_all_pseudonyms: true) + SisPseudonym.for(enrollment.user, root_account, include_all_pseudonyms: true) pseudonym_sis_ids = sis_pseudonyms ? sis_pseudonyms.map(&:sis_user_id) : [nil] pseudonym_sis_ids.each do |pseudonym_sis_id| @@ -2151,7 +2151,7 @@ def generate_grade_publishing_csv_output(enrollments, publishing_user, publishin enrollment.workflow_state, score ] - row << grade if self.grading_standard_enabled? + row << grade if grading_standard_enabled? csv << row end end @@ -2165,9 +2165,9 @@ def generate_grade_publishing_csv_output(enrollments, publishing_user, publishin end def expire_pending_grade_publishing_statuses(last_publish_attempt_at) - self.student_enrollments.not_fake.where(:grade_publishing_status => ['pending', 'publishing'], - :last_publish_attempt_at => last_publish_attempt_at) - .update_all(:grade_publishing_status => 'error', :grade_publishing_message => "Timed out.") + student_enrollments.not_fake.where(:grade_publishing_status => ['pending', 'publishing'], + :last_publish_attempt_at => last_publish_attempt_at) + .update_all(:grade_publishing_status => 'error', :grade_publishing_message => "Timed out.") end def gradebook_to_csv_in_background(filename, user, options = {}) @@ -2211,15 +2211,15 @@ def create_attachment(attachment, csv) alias_attribute :sis_course_id, :sis_source_id def grading_standard_title - if self.grading_standard_enabled? - self.grading_standard.try(:title) || t('default_grading_scheme_name', "Default Grading Scheme") + if grading_standard_enabled? + grading_standard.try(:title) || t('default_grading_scheme_name', "Default Grading Scheme") else nil end end def score_to_grade(score) - return nil unless self.grading_standard_enabled? && score + return nil unless grading_standard_enabled? && score if grading_standard grading_standard.score_to_grade(score) @@ -2229,7 +2229,7 @@ def score_to_grade(score) end def active_course_level_observers - participating_observers.observing_full_course(self.id) + participating_observers.observing_full_course(id) end def participants(opts = {}) @@ -2247,15 +2247,15 @@ def participants(opts = {}) participants += applicable_students if opts[:include_observers] - participants += User.observing_students_in_course(applicable_students.map(&:id), self.id) - participants += User.observing_full_course(self.id) + participants += User.observing_students_in_course(applicable_students.map(&:id), id) + participants += User.observing_full_course(id) end participants.uniq end def filter_users_by_permission(users, permission) - scope = self.enrollments.where(:user_id => users) + scope = enrollments.where(:user_id => users) details = RoleOverride.permissions[permission] scope = details[:applies_to_concluded] ? scope.not_inactive_by_date : scope.active_or_pending_by_date @@ -2278,27 +2278,27 @@ def enroll_user(user, type = 'StudentEnrollment', opts = {}) limit_privileges_to_course_section = opts[:limit_privileges_to_course_section] || false associated_user_id = opts[:associated_user_id] - role = opts[:role] || self.shard.activate { Enrollment.get_built_in_role_for_type(type, root_account_id: self.root_account_id) } + role = opts[:role] || shard.activate { Enrollment.get_built_in_role_for_type(type, root_account_id: self.root_account_id) } start_at = opts[:start_at] end_at = opts[:end_at] self_enrolled = opts[:self_enrolled] - section ||= self.default_section - enrollment_state ||= self.available? ? "invited" : "creation_pending" + section ||= default_section + enrollment_state ||= available? ? "invited" : "creation_pending" if type == 'TeacherEnrollment' || type == 'TaEnrollment' || type == 'DesignerEnrollment' enrollment_state = 'invited' if enrollment_state == 'creation_pending' else - enrollment_state = 'creation_pending' if enrollment_state == 'invited' && !self.available? + enrollment_state = 'creation_pending' if enrollment_state == 'invited' && !available? end Course.unique_constraint_retry do e = if opts[:allow_multiple_enrollments] - self.all_enrollments.where(user_id: user, type: type, role_id: role, associated_user_id: associated_user_id, course_section_id: section.id).first + all_enrollments.where(user_id: user, type: type, role_id: role, associated_user_id: associated_user_id, course_section_id: section.id).first else # order by course_section_id<>section.id so that if there *is* an existing enrollment for this section, we get it (false orders before true) - self.all_enrollments - .where(user_id: user, type: type, role_id: role, associated_user_id: associated_user_id) - .order(Arel.sql("course_section_id<>#{section.id}")) - .first + all_enrollments + .where(user_id: user, type: type, role_id: role, associated_user_id: associated_user_id) + .order(Arel.sql("course_section_id<>#{section.id}")) + .first end if e && (!e.active? || opts[:force_update]) e.already_enrolled = true @@ -2316,7 +2316,7 @@ def enroll_user(user, type = 'StudentEnrollment', opts = {}) # subclass, but without using associations, we need to manually activate # sharding. We should probably find a way to go back to using the # association here -- just ran out of time. - self.shard.activate do + shard.activate do e ||= Enrollment.typed_enrollment(type).new( :user => user, :course => self, @@ -2340,7 +2340,7 @@ def enroll_user(user, type = 'StudentEnrollment', opts = {}) end end e.user = user - self.claim if self.created? && e && e.admin? + claim if created? && e && e.admin? unless opts[:skip_touch_user] e.associated_user.try(:touch) user.touch @@ -2382,7 +2382,7 @@ def resubmission_for(asset) end def grading_standard_enabled - !!self.grading_standard_id + !!grading_standard_id end alias_method :grading_standard_enabled?, :grading_standard_enabled @@ -2395,7 +2395,7 @@ def grading_standard_enabled=(val) end def readable_default_wiki_editing_roles - roles = self.default_wiki_editing_roles || "teachers" + roles = default_wiki_editing_roles || "teachers" case roles when 'teachers,students' t('wiki_permissions.teachers_students', 'Teacher and Students') @@ -2432,8 +2432,8 @@ def default_section(opts = {}) end def assert_section - if self.course_sections.active.empty? - default = self.default_section + if course_sections.active.empty? + default = default_section default.workflow_state = 'active' default.save end @@ -2446,25 +2446,25 @@ def file_structure_for(user) delegate :turnitin_settings, to: :account def turnitin_pledge - self.account.closest_turnitin_pledge + account.closest_turnitin_pledge end def turnitin_originality - self.account.closest_turnitin_originality + account.closest_turnitin_originality end def all_turnitin_comments - comments = self.account.closest_turnitin_comments || "" - if self.turnitin_comments && !self.turnitin_comments.empty? + comments = account.closest_turnitin_comments || "" + if turnitin_comments && !turnitin_comments.empty? comments += "\n\n" if comments && !comments.empty? - comments += self.turnitin_comments + comments += turnitin_comments end - self.extend TextHelper + extend TextHelper format_message(comments).first end def turnitin_enabled? - !!self.turnitin_settings + !!turnitin_settings end def vericite_enabled? @@ -2608,7 +2608,7 @@ def self.clonable_attributes end def student_reporting? - !!self.allow_student_discussion_reporting + !!allow_student_discussion_reporting end def set_course_dates_if_blank(shift_options) @@ -2625,7 +2625,7 @@ def real_start_date end def all_dates - (self.calendar_events.active + self.assignments.active).each_with_object([]) { |e, list| + (calendar_events.active + assignments.active).each_with_object([]) { |e, list| list << e.end_at if e.end_at list << e.start_at if e.start_at }.compact.flatten.map(&:to_date).uniq rescue [] @@ -2647,9 +2647,9 @@ def self.serialization_excludes # helper method to DRY-up some similar methods that all can be cached based on a user's enrollments def fetch_on_enrollments(key, user, opts = nil, &block) - self.shard.activate do + shard.activate do RequestCache.cache(key, user, self, opts) do - Rails.cache.fetch_with_batched_keys([key, self.global_asset_string, opts].compact.cache_key, batch_object: user, batched_keys: :enrollments) do + Rails.cache.fetch_with_batched_keys([key, global_asset_string, opts].compact.cache_key, batch_object: user, batched_keys: :enrollments) do GuardRail.activate(:primary, &block) end end @@ -2692,18 +2692,18 @@ def students_visible_to(user, include: nil) include = Array(include) if include.include?(:priors_and_deleted) - scope = self.all_students_including_deleted + scope = all_students_including_deleted elsif include.include?(:priors) - scope = self.all_students + scope = all_students elsif include.include?(:inactive) || include.include?(:completed) - scope = self.all_accepted_students + scope = all_accepted_students scope = scope.where("enrollments.workflow_state<>'inactive'") unless include.include?(:inactive) scope = scope.where("enrollments.workflow_state<>'completed'") unless include.include?(:completed) else - scope = self.students + scope = students end - self.apply_enrollment_visibility(scope, user, nil, include: include) + apply_enrollment_visibility(scope, user, nil, include: include) end # can apply to user scopes as well if through enrollments (e.g. students, teachers) @@ -2822,7 +2822,7 @@ def enrollment_visibility_level_for(user, visibilities = section_visibilities_for(user), require_message_permission: false, check_full: true) - manage_perm = if self.root_account.feature_enabled? :granular_permissions_manage_users + manage_perm = if root_account.feature_enabled? :granular_permissions_manage_users :allow_course_admin_actions else :manage_admin_users @@ -2863,11 +2863,11 @@ def invited_count_visible_to(user) end def published? - self.available? || self.completed? + available? || completed? end def unpublished? - self.created? || self.claimed? + created? || claimed? end def tab_configuration @@ -3038,12 +3038,12 @@ def tab_enabled?(tab) end def tab_hidden?(id) - tab = self.tab_configuration.find { |t| t[:id] == id } + tab = tab_configuration.find { |t| t[:id] == id } tab && tab[:hidden] end def external_tool_tabs(opts, user) - tools = self.context_external_tools.active.having_setting('course_navigation') + tools = context_external_tools.active.having_setting('course_navigation') tools += ContextExternalTool.active.having_setting('course_navigation').where(context_type: 'Account', context_id: account_chain_ids).to_a tools = tools.select { |t| t.permission_given?(:course_navigation, user, self) && t.feature_flag_enabled?(self) } Lti::ExternalToolTab.new(self, :course_navigation, tools, opts[:language]).tabs @@ -3087,7 +3087,7 @@ def uncached_tabs_available(user, opts) GuardRail.activate(:secondary) do # We will by default show everything in default_tabs, unless the teacher has configured otherwise. - tabs = elementary_subject_course? && !course_subject_tabs ? [] : self.tab_configuration.compact + tabs = elementary_subject_course? && !course_subject_tabs ? [] : tab_configuration.compact home_tab = default_tabs.find { |t| t[:id] == TAB_HOME } settings_tab = default_tabs.find { |t| t[:id] == TAB_SETTINGS } external_tabs = if opts[:include_external] @@ -3149,7 +3149,7 @@ def uncached_tabs_available(user, opts) if opts[:precalculated_permissions]&.key?(permission) opts[:precalculated_permissions][permission] else - self.grants_right?(user, opts[:session], permission) + grants_right?(user, opts[:session], permission) end end end @@ -3176,7 +3176,7 @@ def uncached_tabs_available(user, opts) tabs_that_can_be_marked_hidden_unused.reject! { |t| t[:id] == TAB_MODULES } # Hide Groups tab for students if there are no groups - unless self.grants_right?(user, :read_as_admin) || self.active_groups.exists? + unless grants_right?(user, :read_as_admin) || active_groups.exists? tabs.delete_if { |t| t[:id] == TAB_GROUPS } end end @@ -3239,7 +3239,7 @@ def uncached_tabs_available(user, opts) TAB_DISCUSSIONS => [:moderate_forum] } - if self.root_account.feature_enabled?(:granular_permissions_manage_users) + if root_account.feature_enabled?(:granular_permissions_manage_users) additional_checks[TAB_PEOPLE] = RoleOverride::GRANULAR_MANAGE_USER_PERMISSIONS end @@ -3262,7 +3262,7 @@ def allow_wiki_comments end def account_name - self.account.name rescue nil + account.name rescue nil end def term_name @@ -3424,7 +3424,7 @@ def sync_homeroom_participation self.restrict_enrollments_to_course_dates = false self.enrollment_term = linked_homeroom_course.enrollment_term end - self.save! + save! end def sync_homeroom_enrollments(progress = nil) @@ -3432,8 +3432,8 @@ def sync_homeroom_enrollments(progress = nil) progress&.calculate_completion!(0, linked_homeroom_course.enrollments.size) linked_homeroom_course.all_enrollments.find_each do |enrollment| - self.shard.activate do - course_enrollment = if self.shard == enrollment.shard + shard.activate do + course_enrollment = if shard == enrollment.shard all_enrollments.find_or_initialize_by(type: enrollment.type, user_id: enrollment.user_id, role_id: enrollment.role_id, associated_user_id: enrollment.associated_user_id) else # roles don't apply across shards, so fall back to the base type @@ -3483,7 +3483,7 @@ def disable_setting_defaults end def reset_content - self.shard.activate do + shard.activate do Course.transaction do new_course = Course.new keys_to_copy = Course.column_names - [ @@ -3491,10 +3491,10 @@ def reset_content :tab_configuration, :lti_context_id, :workflow_state, :latest_outcome_import_id, :grading_standard_id ].map(&:to_s) - self.attributes.each do |key, val| + attributes.each do |key, val| new_course.write_attribute(key, val) if keys_to_copy.include?(key) end - new_course.workflow_state = (self.admins.any? ? 'claimed' : 'created') + new_course.workflow_state = (admins.any? ? 'claimed' : 'created') # there's a unique constraint on this, so we need to clear it out self.self_enrollment_code = nil self.self_enrollment = false @@ -3504,9 +3504,9 @@ def reset_content # deleted has to be last otherwise it would set all the enrollments to # deleted before they got moved self.uuid = self.sis_source_id = self.sis_batch_id = self.integration_id = nil - self.save! + save! Course.process_as_sis { new_course.save! } - self.course_sections.update_all(:course_id => new_course.id) + course_sections.update_all(:course_id => new_course.id) # we also want to bring along prior enrollments, so don't use the enrollments # association Enrollment.where(:course_id => self).update_all(:course_id => new_course.id, :updated_at => Time.now.utc) @@ -3515,14 +3515,14 @@ def reset_content User.touch_and_clear_cache_keys(user_ids, :enrollments) end Shard.partition_by_shard(user_ids) do |sharded_user_ids| - Favorite.where(:user_id => sharded_user_ids, :context_type => "Course", :context_id => self.id) + Favorite.where(:user_id => sharded_user_ids, :context_type => "Course", :context_id => id) .update_all(:context_id => new_course.id, :updated_at => Time.now.utc) end self.replacement_course_id = new_course.id self.workflow_state = 'deleted' Course.suspend_callbacks(:copy_from_course_template) do - self.save! + save! end unless profile.new_record? @@ -3535,10 +3535,10 @@ def reset_content end def user_list_search_mode_for(user) - if self.root_account.open_registration? - return self.root_account.delegated_authentication? ? :preferred : :open + if root_account.open_registration? + return root_account.delegated_authentication? ? :preferred : :open end - return :preferred if self.root_account.grants_right?(user, :manage_user_logins) + return :preferred if root_account.grants_right?(user, :manage_user_logins) :closed end @@ -3548,7 +3548,7 @@ def default_home_page end def participating_users(user_ids) - User.where(:id => self.enrollments.active_by_date.where(:user_id => user_ids).select(:user_id)) + User.where(:id => enrollments.active_by_date.where(:user_id => user_ids).select(:user_id)) end def student_view_student @@ -3561,22 +3561,22 @@ def student_view_student # account_associations. if either of these conditions is false, something is # wrong. def find_or_create_student_view_student - if self.student_view_students.active.count == 0 + if student_view_students.active.count == 0 fake_student = nil User.skip_updating_account_associations do fake_student = User.new(:name => t('student_view_student_name', "Test Student")) fake_student.preferences[:fake_student] = true fake_student.workflow_state = 'registered' - fake_student.shard = self.shard + fake_student.shard = shard fake_student.save # hash the unique_id so that it's hard to accidently enroll the user in # a course by entering something in a user list. :( - fake_student.pseudonyms.create!(:account => self.root_account, + fake_student.pseudonyms.create!(:account => root_account, :unique_id => Canvas::Security.hmac_sha1("Test Student_#{fake_student.id}")) end fake_student else - self.student_view_students.active.first + student_view_students.active.first end end private :find_or_create_student_view_student @@ -3584,16 +3584,16 @@ def find_or_create_student_view_student # we want to make sure the student view student is always enrolled in all the # sections of the course, so that a section limited teacher can grade them. def sync_enrollments(fake_student) - self.default_section unless course_sections.active.any? + default_section unless course_sections.active.any? Enrollment.suspend_callbacks(:set_update_cached_due_dates) do - self.course_sections.active.each do |section| + course_sections.active.each do |section| # enroll fake_student will only create the enrollment if it doesn't already exist - self.enroll_user(fake_student, 'StudentViewEnrollment', - :allow_multiple_enrollments => true, - :section => section, - :enrollment_state => 'active', - :no_notify => true, - :skip_touch_user => true) + enroll_user(fake_student, 'StudentViewEnrollment', + :allow_multiple_enrollments => true, + :section => section, + :enrollment_state => 'active', + :no_notify => true, + :skip_touch_user => true) end end DueDateCacher.recompute_users_for_course(fake_student.id, self) @@ -3620,28 +3620,28 @@ def update_one(update_params, user, update_source = :manual) case update_params[:event] when 'offer' - if self.completed? - self.unconclude! + if completed? + unconclude! Auditors::Course.record_unconcluded(self, user, options) else - unless self.available? - self.offer! + unless available? + offer! Auditors::Course.record_published(self, user, options) end end when 'conclude' - unless self.completed? - self.complete! + unless completed? + complete! Auditors::Course.record_concluded(self, user, options) end when 'delete' self.sis_source_id = nil self.workflow_state = 'deleted' - self.save! + save! Auditors::Course.record_deleted(self, user, options) when 'undelete' self.workflow_state = 'claimed' - self.save! + save! Auditors::Course.record_restored(self, user, options) end end @@ -3679,7 +3679,7 @@ def self.batch_update(account, user, course_ids, update_params, update_source = end def re_send_invitations!(from_user) - self.apply_enrollment_visibility(self.student_enrollments, from_user).invited.except(:preload).preload(user: :communication_channels).find_each do |e| + apply_enrollment_visibility(student_enrollments, from_user).invited.except(:preload).preload(user: :communication_channels).find_each do |e| e.re_send_confirmation! if e.invited? end end @@ -3692,7 +3692,7 @@ def serialize_permissions(permissions_hash, user, session) end def active_section_count - @section_count ||= self.active_course_sections.count + @section_count ||= active_course_sections.count end def multiple_sections? @@ -3700,10 +3700,10 @@ def multiple_sections? end def content_exports_visible_to(user) - if self.grants_right?(user, :read_as_admin) - self.content_exports.admin(user) + if grants_right?(user, :read_as_admin) + content_exports.admin(user) else - self.content_exports.non_admin(user) + content_exports.non_admin(user) end end @@ -3723,28 +3723,28 @@ def touch_content_if_public_visibility_changed(changes = {}, **kwargs) changes = kwargs if changes.empty? && !kwargs.empty? if changes[:is_public] || changes[:is_public_to_auth_users] - self.assignments.touch_all - self.attachments.touch_all - self.calendar_events.touch_all - self.context_modules.touch_all - self.discussion_topics.touch_all - self.quizzes.touch_all - self.wiki.touch - self.wiki_pages.touch_all + assignments.touch_all + attachments.touch_all + calendar_events.touch_all + context_modules.touch_all + discussion_topics.touch_all + quizzes.touch_all + wiki.touch + wiki_pages.touch_all end end def clear_todo_list_cache_later(association_type) - raise "invalid association" unless self.association(association_type).klass == User + raise "invalid association" unless association(association_type).klass == User delay(run_at: 15.seconds.from_now, singleton: "course_clear_cache_#{global_id}_#{association_type}", on_conflict: :loose) .clear_todo_list_cache(association_type) end def clear_todo_list_cache(association_type) - raise "invalid association" unless self.association(association_type).klass == User + raise "invalid association" unless association(association_type).klass == User - self.send(association_type).clear_cache_keys(:todo_list) + send(association_type).clear_cache_keys(:todo_list) end def touch_admins # TODO remove after existing jobs run @@ -3752,7 +3752,7 @@ def touch_admins # TODO remove after existing jobs run end def clear_caches_if_necessary - self.clear_cache_key(:account_associations) if saved_change_to_root_account_id? || saved_change_to_account_id? + clear_cache_key(:account_associations) if saved_change_to_root_account_id? || saved_change_to_account_id? end def refresh_content_participation_counts(_progress) @@ -3775,7 +3775,7 @@ def nickname_for(user, fallback = :name, prefer_friendly_name: true) return friendly_name if prefer_friendly_name && friendly_name.present? nickname = preloaded_nickname? ? @preloaded_nickname : user&.course_nickname(self) - nickname ||= self.send(fallback) if fallback + nickname ||= send(fallback) if fallback nickname end @@ -3931,7 +3931,7 @@ def apply_post_policy!(post_manually:) def apply_overridden_course_visibility(visibility) self.overridden_course_visibility = if !['institution', 'public', 'course'].include?(visibility) && - self.root_account.available_course_visibility_override_options.key?(visibility) + root_account.available_course_visibility_override_options.key?(visibility) visibility else nil @@ -3952,9 +3952,9 @@ def apply_visibility_configuration(course_visibility, syllabus_visibility) end if syllabus_visibility.present? - if self.is_public || syllabus_visibility == 'public' + if is_public || syllabus_visibility == 'public' self.public_syllabus = true - elsif self.is_public_to_auth_users || syllabus_visibility == 'institution' + elsif is_public_to_auth_users || syllabus_visibility == 'institution' self.public_syllabus_to_auth = true self.public_syllabus = false else diff --git a/app/models/course_account_association.rb b/app/models/course_account_association.rb index c1dd978588042..25284f6495a4d 100644 --- a/app/models/course_account_association.rb +++ b/app/models/course_account_association.rb @@ -31,9 +31,9 @@ class CourseAccountAssociation < ActiveRecord::Base def set_root_account_id self.root_account_id ||= if account.root_account? - self.account.id + account.id else - self.account&.root_account_id + account&.root_account_id end end end diff --git a/app/models/course_section.rb b/app/models/course_section.rb index 2059138f64fac..4b4d5ba4a2cfa 100644 --- a/app/models/course_section.rb +++ b/app/models/course_section.rb @@ -62,7 +62,7 @@ class CourseSection < ActiveRecord::Base def validate_section_dates if start_at.present? && end_at.present? && end_at < start_at - self.errors.add(:end_at, t("End date cannot be before start date")) + errors.add(:end_at, t("End date cannot be before start date")) false else true @@ -70,7 +70,7 @@ def validate_section_dates end def maybe_touch_all_enrollments - self.touch_all_enrollments if self.start_at_changed? || self.end_at_changed? || self.restrict_enrollments_to_section_dates_changed? || self.course_id_changed? + touch_all_enrollments if start_at_changed? || end_at_changed? || restrict_enrollments_to_section_dates_changed? || course_id_changed? end def delete_enrollments_later_if_deleted @@ -79,7 +79,7 @@ def delete_enrollments_later_if_deleted def delete_enrollments_if_deleted if workflow_state == 'deleted' - self.enrollments.where.not(workflow_state: 'deleted').find_in_batches do |batch| + enrollments.where.not(workflow_state: 'deleted').find_in_batches do |batch| Enrollment::BatchStateUpdater.destroy_batch(batch) end end @@ -125,17 +125,17 @@ def participants(opts = {}) def concluded? now = Time.now - if self.end_at && self.restrict_enrollments_to_section_dates - self.end_at < now + if end_at && restrict_enrollments_to_section_dates + end_at < now else - self.course.concluded? + course.concluded? end end def touch_all_enrollments return if new_record? - self.enrollments.touch_all + enrollments.touch_all User.where(id: all_enrollments.select(:user_id)).touch_all end @@ -145,110 +145,110 @@ def broadcast_data set_policy do given do |user, session| - self.course.grants_right?(user, session, :manage_sections_add) + course.grants_right?(user, session, :manage_sections_add) end can :read and can :create given do |user, session| - self.course.grants_right?(user, session, :manage_sections_edit) + course.grants_right?(user, session, :manage_sections_edit) end can :read and can :update given do |user, session| - self.course.grants_right?(user, session, :manage_sections_delete) + course.grants_right?(user, session, :manage_sections_delete) end can :read and can :delete given do |user, session| - manage_perm = if self.root_account.feature_enabled? :granular_permissions_manage_users + manage_perm = if root_account.feature_enabled? :granular_permissions_manage_users :allow_course_admin_actions else :manage_admin_users end - self.course.grants_any_right?(user, session, :manage_students, manage_perm) + course.grants_any_right?(user, session, :manage_students, manage_perm) end can :read - given { |user| self.course.account_membership_allows(user, :read_roster) } + given { |user| course.account_membership_allows(user, :read_roster) } can :read - given { |user, session| self.course.grants_right?(user, session, :manage_calendar) } + given { |user, session| course.grants_right?(user, session, :manage_calendar) } can :manage_calendar given { |user, session| user && - self.course.sections_visible_to(user).where(:id => self).exists? && - self.course.grants_right?(user, session, :read_roster) + course.sections_visible_to(user).where(:id => self).exists? && + course.grants_right?(user, session, :read_roster) } can :read - given { |user, session| self.course.grants_right?(user, session, :manage_grades) } + given { |user, session| course.grants_right?(user, session, :manage_grades) } can :manage_grades - given { |user, session| self.course.grants_right?(user, session, :read_as_admin) } + given { |user, session| course.grants_right?(user, session, :read_as_admin) } can :read_as_admin end def update_account_associations_if_changed - if (self.saved_change_to_course_id? || self.saved_change_to_nonxlist_course_id?) && !Course.skip_updating_account_associations? - Course.delay_if_production(n_strand: ["update_account_associations", self.root_account_id]) - .update_account_associations([self.course_id, self.course_id_before_last_save, self.nonxlist_course_id, self.nonxlist_course_id_before_last_save].compact.uniq) + if (saved_change_to_course_id? || saved_change_to_nonxlist_course_id?) && !Course.skip_updating_account_associations? + Course.delay_if_production(n_strand: ["update_account_associations", root_account_id]) + .update_account_associations([course_id, course_id_before_last_save, nonxlist_course_id, nonxlist_course_id_before_last_save].compact.uniq) end end def update_account_associations - Course.update_account_associations([self.course_id, self.nonxlist_course_id].compact) + Course.update_account_associations([course_id, nonxlist_course_id].compact) end def verify_unique_sis_source_id - return true unless self.sis_source_id + return true unless sis_source_id return true if !root_account_id_changed? && !sis_source_id_changed? - scope = root_account.course_sections.where(sis_source_id: self.sis_source_id) - scope = scope.where("id<>?", self) unless self.new_record? + scope = root_account.course_sections.where(sis_source_id: sis_source_id) + scope = scope.where("id<>?", self) unless new_record? return true unless scope.exists? - self.errors.add(:sis_source_id, t('sis_id_taken', "SIS ID \"%{sis_id}\" is already in use", :sis_id => self.sis_source_id)) + errors.add(:sis_source_id, t('sis_id_taken', "SIS ID \"%{sis_id}\" is already in use", :sis_id => sis_source_id)) throw :abort end def verify_unique_integration_id - return true unless self.integration_id + return true unless integration_id return true if !root_account_id_changed? && !integration_id_changed? - scope = root_account.course_sections.where(integration_id: self.integration_id) - scope = scope.where("id<>?", self) unless self.new_record? + scope = root_account.course_sections.where(integration_id: integration_id) + scope = scope.where("id<>?", self) unless new_record? return true unless scope.exists? - self.errors.add(:integration_id, t('integration_id_taken', "INTEGRATRION ID \"%{integration_id}\" is already in use", :integration_id => self.integration_id)) + errors.add(:integration_id, t('integration_id_taken', "INTEGRATRION ID \"%{integration_id}\" is already in use", :integration_id => integration_id)) throw :abort end alias_method :parent_event_context, :course def section_code - self.name + name end def infer_defaults - self.root_account_id ||= (self.course.root_account_id rescue nil) || Account.default.id - raise "Course required" unless self.course + self.root_account_id ||= (course.root_account_id rescue nil) || Account.default.id + raise "Course required" unless course - self.root_account_id = self.course.root_account_id || Account.default.id + self.root_account_id = course.root_account_id || Account.default.id # This is messy, and I hate it. # The SIS import actually gives us three names for a section # and I don't know which one is best, or which one to show. # Here's the current plan: # - otherwise, just use name # - use the method display_name to consolidate this logic - self.name ||= self.course.name if self.default_section - self.name ||= "#{self.course.name} #{Time.zone.today}" + self.name ||= course.name if default_section + self.name ||= "#{course.name} #{Time.zone.today}" end def defined_by_sis? - !!self.sis_source_id + !!sis_source_id end # NOTE: Don't assume the section_name contains the course name @@ -262,20 +262,20 @@ def display_name end def move_to_course(course, **opts) - return self if self.course_id == course.id + return self if course_id == course.id old_course = self.course self.course = course self.root_account_id = course.root_account_id all_attrs = { course_id: course.id } - if self.root_account_id_changed? + if root_account_id_changed? all_attrs[:root_account_id] = self.root_account_id end CourseSection.unique_constraint_retry do self.default_section = (course.course_sections.active.empty?) - self.save! + save! end old_course.course_sections.reset @@ -283,12 +283,12 @@ def move_to_course(course, **opts) assignment_overrides.active.destroy_all discussion_topic_section_visibilities.active.destroy_all - enrollment_data = self.all_enrollments.pluck(:id, :user_id) + enrollment_data = all_enrollments.pluck(:id, :user_id) enrollment_ids = enrollment_data.map(&:first) user_ids = enrollment_data.map(&:last).uniq if enrollment_ids.any? - self.all_enrollments.update_all all_attrs + all_enrollments.update_all all_attrs Enrollment.delay_if_production.batch_add_to_favorites(enrollment_ids) end @@ -297,10 +297,10 @@ def move_to_course(course, **opts) end User.clear_cache_keys(user_ids, :enrollments) - EnrollmentState.delay_if_production(n_strand: ["invalidate_enrollment_states", self.global_root_account_id]) + EnrollmentState.delay_if_production(n_strand: ["invalidate_enrollment_states", global_root_account_id]) .invalidate_states_for_course_or_section(self, invalidate_access: true) User.delay_if_production.update_account_associations(user_ids) if old_course.account_id != course.account_id && !User.skip_updating_account_associations? - if old_course.id != self.course_id && old_course.id != self.nonxlist_course_id + if old_course.id != course_id && old_course.id != nonxlist_course_id old_course.delay_if_production.update_account_associations unless Course.skip_updating_account_associations? end @@ -318,26 +318,26 @@ def move_to_course(course, **opts) end def ensure_enrollments_in_correct_section - self.enrollments.where.not(:course_id => self.course_id).each { |e| e.update_attribute(:course_id, self.course_id) } + enrollments.where.not(:course_id => course_id).each { |e| e.update_attribute(:course_id, course_id) } end def crosslist_to_course(course, **opts) - return self if self.course_id == course.id + return self if course_id == course.id - self.nonxlist_course_id ||= self.course_id - self.move_to_course(course, **opts) + self.nonxlist_course_id ||= course_id + move_to_course(course, **opts) end def uncrosslist(**opts) return unless self.nonxlist_course_id - if self.nonxlist_course.workflow_state == "deleted" - self.nonxlist_course.workflow_state = "claimed" - self.nonxlist_course.save! + if nonxlist_course.workflow_state == "deleted" + nonxlist_course.workflow_state = "claimed" + nonxlist_course.save! end nonxlist_course = self.nonxlist_course self.nonxlist_course = nil - self.move_to_course(nonxlist_course, **opts) + move_to_course(nonxlist_course, **opts) end def crosslisted? @@ -345,17 +345,17 @@ def crosslisted? end def destroy_course_if_no_more_sections - if self.deleted? && self.course.course_sections.active.empty? - self.course.destroy + if deleted? && course.course_sections.active.empty? + course.destroy end end def deletable? - !self.enrollments.where.not(:workflow_state => 'rejected').not_fake.exists? + !enrollments.where.not(:workflow_state => 'rejected').not_fake.exists? end def enroll_user(user, type, state = 'invited') - self.course.enroll_user(user, type, :enrollment_state => state, :section => self) + course.enroll_user(user, type, :enrollment_state => state, :section => self) end workflow do @@ -366,9 +366,9 @@ def enroll_user(user, type, state = 'invited') alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.enrollments.not_fake.each(&:destroy) - self.assignment_overrides.each(&:destroy) - self.discussion_topic_section_visibilities&.each(&:destroy) + enrollments.not_fake.each(&:destroy) + assignment_overrides.each(&:destroy) + discussion_topic_section_visibilities&.each(&:destroy) save! end @@ -398,12 +398,12 @@ def self.destroy_batch(batch, sis_batch: nil, batch_mode: false) scope :sis_sections, lambda { |account, *source_ids| where(:root_account_id => account, :sis_source_id => source_ids).order(:sis_source_id) } def common_to_users?(users) - users.all? { |user| self.student_enrollments.active.for_user(user).exists? } + users.all? { |user| student_enrollments.active.for_user(user).exists? } end def update_enrollment_states_if_necessary - if self.saved_change_to_restrict_enrollments_to_section_dates? || (self.restrict_enrollments_to_section_dates? && (saved_changes.keys & %w[start_at end_at]).any?) - EnrollmentState.delay_if_production(n_strand: ["invalidate_enrollment_states", self.global_root_account_id]) + if saved_change_to_restrict_enrollments_to_section_dates? || (restrict_enrollments_to_section_dates? && (saved_changes.keys & %w[start_at end_at]).any?) + EnrollmentState.delay_if_production(n_strand: ["invalidate_enrollment_states", global_root_account_id]) .invalidate_states_for_course_or_section(self) end end diff --git a/app/models/courses/item_visibility_helper.rb b/app/models/courses/item_visibility_helper.rb index 8bdfa0e12b3c0..ec4af5b253c3c 100644 --- a/app/models/courses/item_visibility_helper.rb +++ b/app/models/courses/item_visibility_helper.rb @@ -56,7 +56,7 @@ def cache_visibilities_for_users(item_type, user_ids) def get_visibilities_for_user_ids(item_type, user_ids) GuardRail.activate(:secondary) do - opts = { user_id: user_ids, course_id: [self.id] } + opts = { user_id: user_ids, course_id: [id] } case item_type when :assignment AssignmentStudentVisibility.visible_assignment_ids_in_course_by_user(opts) diff --git a/app/models/crocodoc_document.rb b/app/models/crocodoc_document.rb index 1f37b50e8a158..76fe6f3df3bdb 100644 --- a/app/models/crocodoc_document.rb +++ b/app/models/crocodoc_document.rb @@ -149,9 +149,9 @@ def permissions_for_user(user, allow_list = nil) end def submissions - self.canvadocs_submissions - .preload(submission: :assignment) - .map(&:submission) + canvadocs_submissions + .preload(submission: :assignment) + .map(&:submission) end def apply_allow_list(user, opts, allow_list) diff --git a/app/models/csp/account_helper.rb b/app/models/csp/account_helper.rb index 6c2f7cd1a14ed..bdfd0125e9aff 100644 --- a/app/models/csp/account_helper.rb +++ b/app/models/csp/account_helper.rb @@ -33,7 +33,7 @@ def unload_csp_data def load_csp_data unless @csp_loaded - csp_data = self.csp_inherited_data + csp_data = csp_inherited_data @csp_enabled, @csp_account_id = csp_data&.dig(:value) || [false, nil] @csp_locked = !!csp_data&.dig(:locked) @csp_loaded = true @@ -47,12 +47,12 @@ def csp_enabled? def csp_account_id load_csp_data - @csp_account_id || self.global_id + @csp_account_id || global_id end def csp_inherited? load_csp_data - @csp_account_id != self.global_id + @csp_account_id != global_id end def csp_locked? @@ -65,11 +65,11 @@ def csp_directly_enabled? end def enable_csp! - set_csp_setting!([true, self.global_id]) + set_csp_setting!([true, global_id]) end def disable_csp! - set_csp_setting!([false, self.global_id]) + set_csp_setting!([false, global_id]) end def lock_csp! @@ -81,47 +81,47 @@ def unlock_csp! end def set_csp_locked!(value) - csp_settings = self.settings[:csp_inherited_data].dup + csp_settings = settings[:csp_inherited_data].dup raise "csp not explicitly set" unless csp_settings csp_settings[:locked] = !!value - self.settings[:csp_inherited_data] = csp_settings - self.save! + settings[:csp_inherited_data] = csp_settings + save! end def set_csp_setting!(value) - csp_settings = self.settings[:csp_inherited_data].dup || {} + csp_settings = settings[:csp_inherited_data].dup || {} csp_settings[:value] = value - self.settings[:csp_inherited_data] = csp_settings - self.save! + settings[:csp_inherited_data] = csp_settings + save! end def inherit_csp! - self.settings.delete(:csp_inherited_data) - self.save! + settings.delete(:csp_inherited_data) + save! end def add_domain!(domain) domain = domain.downcase Csp::Domain.unique_constraint_retry do |retry_count| - if retry_count > 0 && (record = self.csp_domains.where(:domain => domain).take) + if retry_count > 0 && (record = csp_domains.where(:domain => domain).take) record.undestroy if record.deleted? record else - record = self.csp_domains.create(:domain => domain) + record = csp_domains.create(:domain => domain) record.valid? && record end end end def remove_domain!(domain) - self.csp_domains.active.where(:domain => domain.downcase).take&.destroy! + csp_domains.active.where(:domain => domain.downcase).take&.destroy! end def csp_whitelisted_domains(request = nil, include_files:, include_tools:) # first, get the allowed domain list from the enabled csp account # then get the list of domains extracted from external tools - domains = ::Csp::Domain.get_cached_domains_for_account(self.csp_account_id) + domains = ::Csp::Domain.get_cached_domains_for_account(csp_account_id) domains += Setting.get('csp.global_whitelist', '').split(',').map(&:strip) domains += cached_tool_domains if include_tools domains += csp_files_domains(request) if include_files @@ -130,7 +130,7 @@ def csp_whitelisted_domains(request = nil, include_files:, include_tools:) ACCOUNT_TOOL_CACHE_KEY_PREFIX = "account_tool_domains" def cached_tool_domains - @cached_tool_domains ||= Rails.cache.fetch([ACCOUNT_TOOL_CACHE_KEY_PREFIX, self.global_id].cache_key) do + @cached_tool_domains ||= Rails.cache.fetch([ACCOUNT_TOOL_CACHE_KEY_PREFIX, global_id].cache_key) do get_account_tool_domains end end @@ -153,7 +153,7 @@ def csp_tool_scope end def clear_tool_domain_cache - Rails.cache.delete([ACCOUNT_TOOL_CACHE_KEY_PREFIX, self.global_id].cache_key) + Rails.cache.delete([ACCOUNT_TOOL_CACHE_KEY_PREFIX, global_id].cache_key) Account.delay_if_production.invalidate_inherited_caches(self, [ACCOUNT_TOOL_CACHE_KEY_PREFIX]) end diff --git a/app/models/csp/course_helper.rb b/app/models/csp/course_helper.rb index 6a70529101b0f..a28a01c784acb 100644 --- a/app/models/csp/course_helper.rb +++ b/app/models/csp/course_helper.rb @@ -23,25 +23,23 @@ def self.included(course_class) end def csp_enabled? - self.account.csp_enabled? && csp_inherited? + account.csp_enabled? && csp_inherited? end def csp_inherited? - csp_locked? || !self.csp_disabled? + csp_locked? || !csp_disabled? end - def csp_locked? - self.account.csp_locked? - end + delegate :csp_locked?, to: :account def inherit_csp! self.csp_disabled = false - self.save! + save! end def disable_csp! self.csp_disabled = true - self.save! + save! end def csp_whitelisted_domains(request = nil, include_files:, include_tools:) @@ -51,13 +49,13 @@ def csp_whitelisted_domains(request = nil, include_files:, include_tools:) end def tool_domain_cache_key - ["course_tool_domains", self.global_id].cache_key + ["course_tool_domains", global_id].cache_key end def cached_tool_domains # invalidate when the course is touched Rails.cache.fetch(tool_domain_cache_key) do - self.context_external_tools.active.map do |tool| + context_external_tools.active.map do |tool| Csp::Domain.domains_for_tool(tool) end.flatten.compact.uniq end diff --git a/app/models/csp/domain.rb b/app/models/csp/domain.rb index 6c0355af457c7..c6920f3e2c6c5 100644 --- a/app/models/csp/domain.rb +++ b/app/models/csp/domain.rb @@ -33,18 +33,18 @@ class Csp::Domain < ActiveRecord::Base after_save :invalidate_domain_list_cache def validate_domain - URI.parse(self.domain) + URI.parse(domain) rescue - self.errors.add(:domain, "Invalid domain") + errors.add(:domain, "Invalid domain") false end def downcase_domain - self.domain = self.domain.downcase + self.domain = domain.downcase end def invalidate_domain_list_cache - self.class.clear_cached_domains(self.global_account_id) + self.class.clear_cached_domains(global_account_id) end def self.get_cached_domains_for_account(global_account_id) @@ -57,7 +57,7 @@ def self.get_cached_domains_for_account(global_account_id) def self.domains_for_account(global_account_id) local_id, shard = Shard.local_id_for(global_account_id) (shard || Shard.current).activate do - self.where(:account_id => local_id).active.pluck(:domain).sort + where(:account_id => local_id).active.pluck(:domain).sort end end diff --git a/app/models/custom_data.rb b/app/models/custom_data.rb index fe2dbe8024185..ccfcb9202ade7 100644 --- a/app/models/custom_data.rb +++ b/app/models/custom_data.rb @@ -52,9 +52,9 @@ def get_data(scope) def lock_and_save transaction do - self.lock! + lock! yield - self.destroyed? || save + destroyed? || save end end @@ -122,7 +122,7 @@ def delete_hash_data_from_scope(hash, scope) end end ret = del_frd.call(hash) - self.destroy if hash.empty? + destroy if hash.empty? ret end diff --git a/app/models/delayed_message.rb b/app/models/delayed_message.rb index d2b0f30f1867f..35f13ca73dcdd 100644 --- a/app/models/delayed_message.rb +++ b/app/models/delayed_message.rb @@ -143,19 +143,19 @@ def self.summarize(delayed_message_ids) def set_send_at # no cc yet = wait - return unless self.communication_channel&.user - return if self.send_at + return unless communication_channel&.user + return if send_at # I got tired of trying to figure out time zones in my head, and I realized # if we do it this way, Rails will take care of it all for us! - if self.frequency == 'weekly' - target = self.communication_channel.user.weekly_notification_time + if frequency == 'weekly' + target = communication_channel.user.weekly_notification_time else # Find the appropriate timezone. For weekly notifications, always use # Eastern. For other notifications, try and user the user's time zone, # defaulting to mountain. (Should be impossible to not find mountain, but # default to system time if necessary.) - time_zone = self.communication_channel.user.time_zone || ActiveSupport::TimeZone['America/Denver'] || Time.zone + time_zone = communication_channel.user.time_zone || ActiveSupport::TimeZone['America/Denver'] || Time.zone target = time_zone.now.change(:hour => 18) target += 1.day if target < time_zone.now end diff --git a/app/models/delayed_notification.rb b/app/models/delayed_notification.rb index 1c8a2d0fec83e..0b33e8e612904 100644 --- a/app/models/delayed_notification.rb +++ b/app/models/delayed_notification.rb @@ -60,17 +60,17 @@ def process res = [] if asset iterate_to_list do |to_list_slice| - slice_res = notification.create_message(self.asset, to_list_slice, data: self.data) + slice_res = notification.create_message(asset, to_list_slice, data: data) res.concat(slice_res) if Rails.env.test? end end - self.do_process unless self.new_record? + do_process unless new_record? res rescue => e Canvas::Errors.capture(e, message: "Delayed Notification processing failed") logger.error "delayed notification processing failed: #{e.message}\n#{e.backtrace.join "\n"}" self.workflow_state = 'errored' - self.save + save [] end diff --git a/app/models/developer_key.rb b/app/models/developer_key.rb index 169d9fb45e590..0750d3a533beb 100644 --- a/app/models/developer_key.rb +++ b/app/models/developer_key.rb @@ -79,7 +79,7 @@ def find_target lti_key_ids = Lti::ToolConfiguration.joins(:developer_key) .where(developer_keys: { id: site_admin_key_ids }) .pluck(:developer_key_id) - self.where(id: lti_key_ids) + where(id: lti_key_ids) end end @@ -98,7 +98,7 @@ def find_target alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.save + save end def usable? @@ -141,7 +141,7 @@ def nullify_empty_icon_url end def generate_api_key(overwrite = false) - self.api_key = CanvasSlug.generate(nil, 64) if overwrite || !self.api_key + self.api_key = CanvasSlug.generate(nil, 64) if overwrite || !api_key end def generate_rsa_keypair!(overwrite: false) @@ -250,7 +250,7 @@ def account_name end def last_used_at - self.access_tokens.maximum(:last_used_at) + access_tokens.maximum(:last_used_at) end # verify that the given uri has the same domain as this key's @@ -284,10 +284,10 @@ def account_binding_for(binding_account) # Search for bindings in the account chain starting with the highest account accounts = Account.account_chain_ids(binding_account).reverse - binding = DeveloperKeyAccountBinding.find_in_account_priority(accounts, self.id) + binding = DeveloperKeyAccountBinding.find_in_account_priority(accounts, id) # If no explicity set bindings were found check for 'allow' bindings - binding ||= DeveloperKeyAccountBinding.find_in_account_priority(accounts.reverse, self.id, false) + binding ||= DeveloperKeyAccountBinding.find_in_account_priority(accounts.reverse, id, false) # Check binding not for wrong account (on different shard) return nil if binding && binding.shard.id != binding_account.shard.id @@ -363,8 +363,8 @@ def tokens_expire_in private def validate_lti_fields - return unless self.is_lti_key? - return if self.public_jwk.present? || self.public_jwk_url.present? + return unless is_lti_key? + return if public_jwk.present? || public_jwk_url.present? errors.add(:lti_key, "developer key must have public jwk or public jwk url") end @@ -376,7 +376,7 @@ def validate_flag_combinations end def normalize_public_jwk_url - self.public_jwk_url = nil if self.public_jwk_url.blank? + self.public_jwk_url = nil if public_jwk_url.blank? end def manage_external_tools(enqueue_args, method, affected_account) @@ -525,15 +525,15 @@ def set_require_scopes end def validate_scopes! - return true if self.scopes.empty? + return true if scopes.empty? - invalid_scopes = self.scopes - TokenScopes.all_scopes + invalid_scopes = scopes - TokenScopes.all_scopes return true if invalid_scopes.empty? - self.errors[:scopes] << "cannot contain #{invalid_scopes.join(', ')}" + errors[:scopes] << "cannot contain #{invalid_scopes.join(', ')}" end def site_admin? - self.account_id.nil? + account_id.nil? end end diff --git a/app/models/developer_key_account_binding.rb b/app/models/developer_key_account_binding.rb index d1151d6ff87f3..ee177aafcc76d 100644 --- a/app/models/developer_key_account_binding.rb +++ b/app/models/developer_key_account_binding.rb @@ -84,7 +84,7 @@ def self.find_site_admin_cached(developer_key) Shard.default.activate do MultiCache.fetch(site_admin_cache_key(developer_key)) do GuardRail.activate(:secondary) do - binding = self.where.not(workflow_state: 'allow').find_by( + binding = where.not(workflow_state: 'allow').find_by( account: Account.site_admin, developer_key: developer_key ) diff --git a/app/models/discussion_entry.rb b/app/models/discussion_entry.rb index 54b2e68e4c94f..e7e61190a3140 100644 --- a/app/models/discussion_entry.rb +++ b/app/models/discussion_entry.rb @@ -116,14 +116,14 @@ def course_broadcast_data end on_create_send_to_streams do - if self.root_entry_id.nil? + if root_entry_id.nil? participants = discussion_topic.active_participants_with_visibility # If the topic has been going for more than two weeks, only show # people who have been participating in the topic - if self.created_at > self.discussion_topic.created_at + 2.weeks + if created_at > discussion_topic.created_at + 2.weeks participants.map(&:id) & DiscussionEntry.active - .where('discussion_topic_id=? AND created_at > ?', self.discussion_topic_id, 2.weeks.ago) + .where('discussion_topic_id=? AND created_at > ?', discussion_topic_id, 2.weeks.ago) .distinct.pluck(:user_id) else participants @@ -139,12 +139,12 @@ def self.max_depth end def self.rating_sums(entry_ids) - sums = self.where(:id => entry_ids).where('COALESCE(rating_sum, 0) != 0') + sums = where(:id => entry_ids).where('COALESCE(rating_sum, 0) != 0') sums.map { |x| [x.id, x.rating_sum] }.to_h end def set_depth - self.depth ||= (self.parent_entry.try(:depth) || 0) + 1 + self.depth ||= (parent_entry.try(:depth) || 0) + 1 end def validate_depth @@ -154,18 +154,18 @@ def validate_depth end def discussion_not_deleted - errors.add(:base, "Requires non-deleted discussion topic") if self.discussion_topic.deleted? + errors.add(:base, "Requires non-deleted discussion topic") if discussion_topic.deleted? end def must_be_reply_to_same_discussion - if self.parent_entry && self.parent_entry.discussion_topic_id != self.discussion_topic_id + if parent_entry && parent_entry.discussion_topic_id != discussion_topic_id errors.add(:parent_id, "Parent entry must belong to the same discussion topic") end end def reply_from(opts) - raise IncomingMail::Errors::UnknownAddress if self.context.root_account.deleted? - raise IncomingMail::Errors::ReplyToDeletedDiscussion if self.discussion_topic.deleted? + raise IncomingMail::Errors::UnknownAddress if context.root_account.deleted? + raise IncomingMail::Errors::ReplyToDeletedDiscussion if discussion_topic.deleted? user = opts[:user] if opts[:html] @@ -174,11 +174,11 @@ def reply_from(opts) message = opts[:text].strip message = format_message(message).first end - user = nil unless user && self.context.users.include?(user) + user = nil unless user && context.users.include?(user) if !user raise IncomingMail::Errors::InvalidParticipant else - self.shard.activate do + shard.activate do entry = discussion_topic.discussion_entries.new(message: message, user: user, parent_entry: self) @@ -205,7 +205,7 @@ def summary(length = 150) end def plaintext_message(length = 250) - truncate_html(self.message, :max_length => length) + truncate_html(message, :max_length => length) end alias_method :destroy_permanently!, :destroy @@ -219,26 +219,26 @@ def destroy end def update_discussion - if %w[workflow_state message attachment_id editor_id].any? { |a| self.saved_change_to_attribute?(a) } - dt = self.discussion_topic + if %w[workflow_state message attachment_id editor_id].any? { |a| saved_change_to_attribute?(a) } + dt = discussion_topic loop do dt.touch dt = dt.root_topic break if dt.blank? end - self.class.connection.after_transaction_commit { self.discussion_topic.update_materialized_view } + self.class.connection.after_transaction_commit { discussion_topic.update_materialized_view } end end def update_topic_submission - if self.discussion_topic.for_assignment? - entries = self.discussion_topic.discussion_entries.where(:user_id => self.user_id, :workflow_state => 'active') - submission = self.discussion_topic.assignment.submissions.where(:user_id => self.user_id).take + if discussion_topic.for_assignment? + entries = discussion_topic.discussion_entries.where(:user_id => user_id, :workflow_state => 'active') + submission = discussion_topic.assignment.submissions.where(:user_id => user_id).take return unless submission if entries.any? submission_date = entries.order(:created_at).limit(1).pluck(:created_at).first - if submission_date > self.created_at + if submission_date > created_at submission.submitted_at = submission_date submission.save! end @@ -259,7 +259,7 @@ def decrement_unread_counts_for_this_entry .where.not(user_id: discussion_entry_participants.read.pluck(:user_id)).pluck(:user_id) # decrement unread_entry_count for topic participants if users.present? - DiscussionTopicParticipant.where(:discussion_topic_id => self.discussion_topic_id, :user_id => users) + DiscussionTopicParticipant.where(:discussion_topic_id => discussion_topic_id, :user_id => users) .update_all('unread_entry_count = unread_entry_count - 1') end end @@ -273,7 +273,7 @@ def update_topic_subscription end def user_name - self.user.name rescue t :default_user_name, "User Name" + user.name rescue t :default_user_name, "User Name" end def populate_legacy @@ -293,10 +293,10 @@ def populate_legacy def infer_root_entry_id # don't allow parent ids for flat discussions - self.parent_entry = nil if self.discussion_topic.discussion_type == DiscussionTopic::DiscussionTypes::FLAT + self.parent_entry = nil if discussion_topic.discussion_type == DiscussionTopic::DiscussionTypes::FLAT # only allow non-root parents for threaded discussions - unless self.discussion_topic.try(:threaded?) + unless discussion_topic.try(:threaded?) self.parent_entry = parent_entry.try(:root_entry) || parent_entry end self.root_entry_id = parent_entry.try(:root_entry_id) || parent_entry.try(:id) @@ -304,9 +304,9 @@ def infer_root_entry_id protected :infer_root_entry_id def update_topic - if self.discussion_topic - last_reply_at = [self.discussion_topic.last_reply_at, self.created_at].compact.max - DiscussionTopic.where(:id => self.discussion_topic_id).update_all(:last_reply_at => last_reply_at, :updated_at => Time.now.utc) + if discussion_topic + last_reply_at = [discussion_topic.last_reply_at, created_at].compact.max + DiscussionTopic.where(:id => discussion_topic_id).update_all(:last_reply_at => last_reply_at, :updated_at => Time.now.utc) end end @@ -314,40 +314,40 @@ def update_topic given { |user| self.user && self.user == user } can :read - given { |user| self.user && self.user == user && self.discussion_topic.available_for?(user) && self.discussion_topic.can_participate_in_course?(user) } + given { |user| self.user && self.user == user && discussion_topic.available_for?(user) && discussion_topic.can_participate_in_course?(user) } can :reply - given { |user| self.user && self.user == user && self.discussion_topic.available_for?(user) && context.user_can_manage_own_discussion_posts?(user) && self.discussion_topic.can_participate_in_course?(user) } + given { |user| self.user && self.user == user && discussion_topic.available_for?(user) && context.user_can_manage_own_discussion_posts?(user) && discussion_topic.can_participate_in_course?(user) } can :update and can :delete - given { |user, session| self.discussion_topic.is_announcement && self.context.grants_right?(user, session, :read_announcements) && self.discussion_topic.visible_for?(user) } + given { |user, session| discussion_topic.is_announcement && context.grants_right?(user, session, :read_announcements) && discussion_topic.visible_for?(user) } can :read - given { |user, session| !self.discussion_topic.is_announcement && self.context.grants_right?(user, session, :read_forum) && self.discussion_topic.visible_for?(user) } + given { |user, session| !discussion_topic.is_announcement && context.grants_right?(user, session, :read_forum) && discussion_topic.visible_for?(user) } can :read - given { |user, session| self.context.grants_right?(user, session, :post_to_forum) && !self.discussion_topic.locked_for?(user) && self.discussion_topic.visible_for?(user) } + given { |user, session| context.grants_right?(user, session, :post_to_forum) && !discussion_topic.locked_for?(user) && discussion_topic.visible_for?(user) } can :reply and can :create and can :read - given { |user, session| self.context.grants_right?(user, session, :post_to_forum) && self.discussion_topic.visible_for?(user) } + given { |user, session| context.grants_right?(user, session, :post_to_forum) && discussion_topic.visible_for?(user) } can :read given { |user, session| context.respond_to?(:allow_student_forum_attachments) && context.allow_student_forum_attachments && context.grants_right?(user, session, :post_to_forum) && discussion_topic.available_for?(user) } can :attach - given { |user, session| !self.discussion_topic.root_topic_id && self.context.grants_right?(user, session, :moderate_forum) && !self.discussion_topic.locked_for?(user, :check_policies => true) } + given { |user, session| !discussion_topic.root_topic_id && context.grants_right?(user, session, :moderate_forum) && !discussion_topic.locked_for?(user, :check_policies => true) } can :update and can :delete and can :reply and can :create and can :read and can :attach - given { |user, session| !self.discussion_topic.root_topic_id && self.context.grants_right?(user, session, :moderate_forum) } + given { |user, session| !discussion_topic.root_topic_id && context.grants_right?(user, session, :moderate_forum) } can :update and can :delete and can :read - given { |user, session| self.discussion_topic.root_topic&.context&.grants_right?(user, session, :moderate_forum) && !self.discussion_topic.locked_for?(user, :check_policies => true) } + given { |user, session| discussion_topic.root_topic&.context&.grants_right?(user, session, :moderate_forum) && !discussion_topic.locked_for?(user, :check_policies => true) } can :update and can :delete and can :reply and can :create and can :read and can :attach - given { |user, session| self.discussion_topic.root_topic&.context&.grants_right?(user, session, :moderate_forum) } + given { |user, session| discussion_topic.root_topic&.context&.grants_right?(user, session, :moderate_forum) } can :update and can :delete and can :read - given { |user, session| self.discussion_topic.grants_right?(user, session, :rate) } + given { |user, session| discussion_topic.grants_right?(user, session, :rate) } can :rate end @@ -368,40 +368,32 @@ def self.participant_join_sql(current_user) end def to_atom(opts = {}) - author_name = self.user.present? ? self.user.name : t('atom_no_author', "No Author") + author_name = user.present? ? user.name : t('atom_no_author', "No Author") Atom::Entry.new do |entry| - subject = [self.discussion_topic.title] - subject << self.discussion_topic.context.name if opts[:include_context] + subject = [discussion_topic.title] + subject << discussion_topic.context.name if opts[:include_context] entry.title = if parent_id t "#subject_reply_to", "Re: %{subject}", :subject => subject.to_sentence else subject.to_sentence end entry.authors << Atom::Person.new(:name => author_name) - entry.updated = self.updated_at - entry.published = self.created_at - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime("%Y-%m-%d")}:/discussion_entries/#{self.feed_code}" + entry.updated = updated_at + entry.published = created_at + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime("%Y-%m-%d")}:/discussion_entries/#{feed_code}" entry.links << Atom::Link.new(:rel => 'alternate', - :href => "http://#{HostUrl.context_host(self.discussion_topic.context)}/#{self.discussion_topic.context_prefix}/discussion_topics/#{self.discussion_topic_id}") - entry.content = Atom::Content::Html.new(self.message) + :href => "http://#{HostUrl.context_host(discussion_topic.context)}/#{discussion_topic.context_prefix}/discussion_topics/#{discussion_topic_id}") + entry.content = Atom::Content::Html.new(message) end end - def context - self.discussion_topic.context - end + delegate :context, to: :discussion_topic - def context_id - self.discussion_topic.context_id - end + delegate :context_id, to: :discussion_topic - def context_type - self.discussion_topic.context_type - end + delegate :context_type, to: :discussion_topic - def title - self.discussion_topic.title - end + delegate :title, to: :discussion_topic def context_module_action_later delay_if_production.context_module_action @@ -411,42 +403,42 @@ def context_module_action_later # If this discussion topic is part of an assignment this method is what # submits the assignment or updates the submission for the user def context_module_action - if self.discussion_topic && self.user - action = self.deleted? ? :deleted : :contributed - self.discussion_topic.context_module_action(user, action) + if discussion_topic && user + action = deleted? ? :deleted : :contributed + discussion_topic.context_module_action(user, action) end end def create_participants self.class.connection.after_transaction_commit do - scope = DiscussionTopicParticipant.where(:discussion_topic_id => self.discussion_topic_id) - if self.discussion_topic.root_topic? - group_ids = self.discussion_topic.group_category.groups.active.pluck(:id) + scope = DiscussionTopicParticipant.where(:discussion_topic_id => discussion_topic_id) + if discussion_topic.root_topic? + group_ids = discussion_topic.group_category.groups.active.pluck(:id) scope = scope.where("NOT EXISTS (?)", GroupMembership.where("group_memberships.workflow_state <> 'deleted' AND group_memberships.user_id=discussion_topic_participants.user_id AND group_memberships.group_id IN (?)", group_ids)) end - scope = scope.where("user_id<>?", self.user) if self.user + scope = scope.where("user_id<>?", user) if user scope.update_all("unread_entry_count = unread_entry_count + 1") - if self.user - update_or_create_participant(current_user: self.user, new_state: 'read') + if user + update_or_create_participant(current_user: user, new_state: 'read') existing_topic_participant = nil DiscussionTopicParticipant.unique_constraint_retry do - existing_topic_participant = self.discussion_topic.discussion_topic_participants.where(user_id: self.user).first + existing_topic_participant = discussion_topic.discussion_topic_participants.where(user_id: user).first unless existing_topic_participant - new_count = self.discussion_topic.default_unread_count - 1 - self.discussion_topic.discussion_topic_participants.create!( - :user => self.user, + new_count = discussion_topic.default_unread_count - 1 + discussion_topic.discussion_topic_participants.create!( + :user => user, :unread_entry_count => new_count, :workflow_state => "unread", - :subscribed => !self.discussion_topic.subscription_hold(user, nil) + :subscribed => !discussion_topic.subscription_hold(user, nil) ) end end - if existing_topic_participant && !existing_topic_participant.subscribed? && !self.discussion_topic.subscription_hold(user, nil) + if existing_topic_participant && !existing_topic_participant.subscribed? && !discussion_topic.subscription_hold(user, nil) existing_topic_participant.update!(:subscribed => true) end end @@ -458,9 +450,9 @@ def clear_planner_cache_for_participants # because the creation of this object will also create a stream item which # takes care of clearing the cache self.class.connection.after_transaction_commit do - if self.root_entry_id.present? - if self.discussion_topic.for_assignment? || self.discussion_topic.todo_date.present? - User.where(:id => self.discussion_topic.discussion_topic_participants.select(:user_id)).touch_all + if root_entry_id.present? + if discussion_topic.for_assignment? || discussion_topic.todo_date.present? + User.where(:id => discussion_topic.discussion_topic_participants.select(:user_id)).touch_all end end end @@ -509,13 +501,13 @@ def change_read_state(new_state, current_user = nil, opts = {}) current_user ||= self.current_user return nil unless current_user - if new_state != self.read_state(current_user) - entry_participant = self.update_or_create_participant( + if new_state != read_state(current_user) + entry_participant = update_or_create_participant( opts.merge(current_user: current_user, new_state: new_state) ) StreamItem.update_read_state_for_asset(self, new_state, current_user.id) if entry_participant.present? - self.discussion_topic.update_or_create_participant( + discussion_topic.update_or_create_participant( opts.merge(current_user: current_user, offset: (new_state == "unread" ? 1 : -1)) ) end @@ -541,12 +533,12 @@ def change_rating(new_rating, current_user = nil) entry_participant = nil transaction do lock! - old_rating = self.rating(current_user) + old_rating = rating(current_user) if new_rating == old_rating return true end - entry_participant = self.update_or_create_participant(current_user: current_user, rating: new_rating).first + entry_participant = update_or_create_participant(current_user: current_user, rating: new_rating).first update_aggregate_rating(old_rating, new_rating) end @@ -557,7 +549,7 @@ def change_rating(new_rating, current_user = nil) def change_report_type(report_type, current_user) return unless report_type && current_user - participant_id = self.update_or_create_participant(current_user: current_user, report_type: report_type).first + participant_id = update_or_create_participant(current_user: current_user, report_type: report_type).first delay.broadcast_report_notification(report_type) if participant_id end @@ -587,7 +579,7 @@ def update_aggregate_rating(old_rating, new_rating) count_delta, sum_delta ]) - self.discussion_topic.update_materialized_view + discussion_topic.update_materialized_view end # Public: Update and save the DiscussionEntryParticipant for a specified user, @@ -647,6 +639,6 @@ def find_existing_participant(user) end def set_root_account_id - self.root_account_id ||= self.discussion_topic.root_account_id + self.root_account_id ||= discussion_topic.root_account_id end end diff --git a/app/models/discussion_entry_participant.rb b/app/models/discussion_entry_participant.rb index ce3b8d463ad93..34763f60caa43 100644 --- a/app/models/discussion_entry_participant.rb +++ b/app/models/discussion_entry_participant.rb @@ -33,29 +33,29 @@ class DiscussionEntryParticipant < ActiveRecord::Base message: "%{value} is not valid" } def prevent_creates - if self.new_record? + if new_record? # e.g. DiscussionEntryParticipant.upsert_for_entries(entry, user, new_state: 'read') - self.errors.add(:base, "Regular creation is disabled on DiscussionEntryParticipant - use upsert_for_entries") + errors.add(:base, "Regular creation is disabled on DiscussionEntryParticipant - use upsert_for_entries") end end def self.read_entry_ids(entry_ids, user) - self.where(:user_id => user, :discussion_entry_id => entry_ids, :workflow_state => 'read') - .pluck(:discussion_entry_id) + where(:user_id => user, :discussion_entry_id => entry_ids, :workflow_state => 'read') + .pluck(:discussion_entry_id) end def self.forced_read_state_entry_ids(entry_ids, user) - self.where(:user_id => user, :discussion_entry_id => entry_ids, :forced_read_state => true) - .pluck(:discussion_entry_id) + where(:user_id => user, :discussion_entry_id => entry_ids, :forced_read_state => true) + .pluck(:discussion_entry_id) end def self.entry_ratings(entry_ids, user) - ratings = self.where(:user_id => user, :discussion_entry_id => entry_ids).where.not(rating: nil) + ratings = where(:user_id => user, :discussion_entry_id => entry_ids).where.not(rating: nil) ratings.map { |x| [x.discussion_entry_id, x.rating] }.to_h end def self.not_null_column_object(column: nil, entry: nil, user: nil) - entry_participant = self.new(discussion_entry: entry, user: user) + entry_participant = new(discussion_entry: entry, user: user) error_message = "Null value in column '#{column}' violates not-null constraint" entry_participant.errors.add(column, error_message) entry_participant @@ -196,6 +196,6 @@ def self.upsert_for_topic(topic, user, new_state: nil, forced: nil, rating: nil) } def set_root_account_id - self.root_account_id = self.discussion_entry.root_account_id + self.root_account_id = discussion_entry.root_account_id end end diff --git a/app/models/discussion_topic.rb b/app/models/discussion_topic.rb index 626bd85b2597b..ffc3d0c293f10 100644 --- a/app/models/discussion_topic.rb +++ b/app/models/discussion_topic.rb @@ -96,7 +96,7 @@ class LockBeforeDueDate < StandardError; end validate :course_group_discussion_cannot_be_section_specific sanitize_field :message, CanvasSanitize::SANITIZE - copy_authorized_links(:message) { [self.context, nil] } + copy_authorized_links(:message) { [context, nil] } acts_as_list scope: { context: self, pinned: true } before_create :initialize_last_reply_at @@ -115,32 +115,32 @@ class LockBeforeDueDate < StandardError; end after_create :create_materialized_view def section_specific_topics_must_have_sections - if !self.deleted? && self.is_section_specific && self.discussion_topic_section_visibilities.none?(&:active?) - self.errors.add(:is_section_specific, t("Section specific topics must have sections")) + if !deleted? && is_section_specific && discussion_topic_section_visibilities.none?(&:active?) + errors.add(:is_section_specific, t("Section specific topics must have sections")) else true end end def only_course_topics_can_be_section_specific - if self.is_section_specific && !(self.context.is_a? Course) - self.errors.add(:is_section_specific, t("Only course announcements and discussions can be section-specific")) + if is_section_specific && !(context.is_a? Course) + errors.add(:is_section_specific, t("Only course announcements and discussions can be section-specific")) else true end end def assignments_cannot_be_section_specific - if self.is_section_specific && self.assignment - self.errors.add(:is_section_specific, t("Discussion assignments cannot be section-specific")) + if is_section_specific && assignment + errors.add(:is_section_specific, t("Discussion assignments cannot be section-specific")) else true end end def course_group_discussion_cannot_be_section_specific - if self.is_section_specific && self.has_group_category? - self.errors.add(:is_section_specific, t("Discussions with groups cannot be section-specific")) + if is_section_specific && has_group_category? + errors.add(:is_section_specific, t("Discussions with groups cannot be section-specific")) else true end @@ -149,14 +149,14 @@ def course_group_discussion_cannot_be_section_specific def sections_for(user) return unless is_section_specific? - CourseSection.where(id: DiscussionTopicSectionVisibility.active.where(discussion_topic_id: self.id) + CourseSection.where(id: DiscussionTopicSectionVisibility.active.where(discussion_topic_id: id) .where("EXISTS (?)", Enrollment.active_or_pending.where(user_id: user) .where("enrollments.course_section_id = discussion_topic_section_visibilities.course_section_id")) .select("discussion_topic_section_visibilities.course_section_id")) end def address_book_context_for(user) - if self.is_section_specific? + if is_section_specific? sections_for(user) else context @@ -168,7 +168,7 @@ def threaded=(v) end def threaded? - self.discussion_type == DiscussionTypes::THREADED || context.feature_enabled?("react_discussions_post") + discussion_type == DiscussionTypes::THREADED || context.feature_enabled?("react_discussions_post") end alias_method :threaded, :threaded? @@ -177,19 +177,19 @@ def discussion_type end def validate_draft_state_change - old_draft_state, new_draft_state = self.changes['workflow_state'] + old_draft_state, new_draft_state = changes['workflow_state'] return if old_draft_state == new_draft_state if new_draft_state == 'unpublished' && !can_unpublish? - self.errors.add :workflow_state, I18n.t('#discussion_topics.error_draft_state_with_posts', - "This topic cannot be set to draft state because it contains posts.") + errors.add :workflow_state, I18n.t('#discussion_topics.error_draft_state_with_posts', + "This topic cannot be set to draft state because it contains posts.") end end def default_values - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" + self.context_code = "#{context_type.underscore}_#{context_id}" - if self.title.blank? + if title.blank? self.title = t('#discussion_topic.default_title', "No Title") end @@ -197,11 +197,11 @@ def default_values d_type ||= context.feature_enabled?("react_discussions_post") ? DiscussionTypes::THREADED : DiscussionTypes::SIDE_COMMENT self.discussion_type = d_type - @content_changed = self.message_changed? || self.title_changed? + @content_changed = message_changed? || title_changed? default_submission_values - if self.has_group_category? + if has_group_category? self.subtopics_refreshed_at ||= Time.zone.parse("Jan 1 2000") end self.lock_at = CanvasTime.fancy_midnight(lock_at&.in_time_zone(context.time_zone)) @@ -215,25 +215,25 @@ def default_values protected :default_values def has_group_category? - !!self.group_category_id + !!group_category_id end def set_schedule_delayed_transitions - @delayed_post_at_changed = self.delayed_post_at_changed? - if self.delayed_post_at? && @delayed_post_at_changed + @delayed_post_at_changed = delayed_post_at_changed? + if delayed_post_at? && @delayed_post_at_changed @should_schedule_delayed_post = true - self.workflow_state = 'post_delayed' if [:migration, :after_migration].include?(self.saved_by) && self.delayed_post_at > Time.now + self.workflow_state = 'post_delayed' if [:migration, :after_migration].include?(saved_by) && delayed_post_at > Time.now end - if self.lock_at && self.lock_at_changed? + if lock_at && lock_at_changed? @should_schedule_lock_at = true - self.locked = false if [:migration, :after_migration].include?(self.saved_by) && self.lock_at > Time.now + self.locked = false if [:migration, :after_migration].include?(saved_by) && lock_at > Time.now end true end def update_materialized_view_if_changed - if self.saved_change_to_sort_by_rating? + if saved_change_to_sort_by_rating? update_materialized_view end end @@ -242,11 +242,11 @@ def update_materialized_view_if_changed def recalculate_progressions_if_sections_changed # either changed sections or undid section specificness - return unless self.is_section_specific? ? @sections_changed : self.is_section_specific_before_last_save + return unless is_section_specific? ? @sections_changed : is_section_specific_before_last_save self.class.connection.after_transaction_commit do - if self.context_module_tags.preload(:context_module).exists? - self.context_module_tags.map(&:context_module).uniq.each do |cm| + if context_module_tags.preload(:context_module).exists? + context_module_tags.map(&:context_module).uniq.each do |cm| cm.invalidate_progressions cm.touch end @@ -255,7 +255,7 @@ def recalculate_progressions_if_sections_changed end def schedule_delayed_transitions - return if self.saved_by == :migration + return if saved_by == :migration bp = true if @importing_migration&.migration_type == 'master_course_import' delay(run_at: delayed_post_at).update_based_on_date(for_blueprint: bp) if @should_schedule_delayed_post @@ -268,31 +268,31 @@ def schedule_delayed_transitions end def sync_attachment_with_publish_state - if (self.saved_change_to_workflow_state? || self.saved_change_to_locked? || self.saved_change_to_attachment_id?) && self.attachment - unless self.attachment.hidden? # if it's already hidden leave alone + if (saved_change_to_workflow_state? || saved_change_to_locked? || saved_change_to_attachment_id?) && attachment + unless attachment.hidden? # if it's already hidden leave alone locked = !!(unpublished? || not_available_yet? || not_available_anymore?) - self.attachment.update_attribute(:locked, locked) + attachment.update_attribute(:locked, locked) end end end def update_subtopics - if !self.deleted? && (self.has_group_category? || !!self.group_category_id_before_last_save) - delay_if_production(singleton: "refresh_subtopics_#{self.global_id}").refresh_subtopics + if !deleted? && (has_group_category? || !!group_category_id_before_last_save) + delay_if_production(singleton: "refresh_subtopics_#{global_id}").refresh_subtopics end end def refresh_subtopics sub_topics = [] - category = self.group_category + category = group_category - if category && self.root_topic_id.blank? && !self.deleted? + if category && root_topic_id.blank? && !deleted? category.groups.active.order(:id).each do |group| sub_topics << ensure_child_topic_for(group) end end - self.shard.activate do + shard.activate do # delete any lingering child topics DiscussionTopic.where(:root_topic_id => self).where.not(:id => sub_topics).update_all(:workflow_state => "deleted") end @@ -303,17 +303,17 @@ def ensure_child_topic_for(group) DiscussionTopic.unique_constraint_retry do topic = DiscussionTopic.where(:context_id => group, :context_type => 'Group', :root_topic_id => self).first topic ||= group.discussion_topics.build { |dt| dt.root_topic = self } - topic.message = self.message - topic.title = CanvasTextHelper.truncate_text("#{self.title} - #{group.name}", { :max_length => 250 }) # because of course people do this - topic.assignment_id = self.assignment_id - topic.attachment_id = self.attachment_id - topic.group_category_id = self.group_category_id - topic.user_id = self.user_id - topic.discussion_type = self.discussion_type - topic.workflow_state = self.workflow_state - topic.allow_rating = self.allow_rating - topic.only_graders_can_rate = self.only_graders_can_rate - topic.sort_by_rating = self.sort_by_rating + topic.message = message + topic.title = CanvasTextHelper.truncate_text("#{title} - #{group.name}", { :max_length => 250 }) # because of course people do this + topic.assignment_id = assignment_id + topic.attachment_id = attachment_id + topic.group_category_id = group_category_id + topic.user_id = user_id + topic.discussion_type = discussion_type + topic.workflow_state = workflow_state + topic.allow_rating = allow_rating + topic.only_graders_can_rate = only_graders_can_rate + topic.sort_by_rating = sort_by_rating topic.save if topic.changed? topic end @@ -321,13 +321,13 @@ def ensure_child_topic_for(group) end def update_assignment - return if self.deleted? + return if deleted? - if !self.assignment_id && @old_assignment_id - self.context_module_tags.each(&:confirm_valid_module_requirements) + if !assignment_id && @old_assignment_id + context_module_tags.each(&:confirm_valid_module_requirements) end if @old_assignment_id - Assignment.where(:id => @old_assignment_id, :context_id => self.context_id, :context_type => self.context_type, :submission_types => 'discussion_topic').update_all(:workflow_state => 'deleted', :updated_at => Time.now.utc) + Assignment.where(:id => @old_assignment_id, :context_id => context_id, :context_type => context_type, :submission_types => 'discussion_topic').update_all(:workflow_state => 'deleted', :updated_at => Time.now.utc) old_assignment = Assignment.find(@old_assignment_id) ContentTag.delete_for(old_assignment) # prevent future syncs from recreating the deleted assignment @@ -336,29 +336,29 @@ def update_assignment own_tag = MasterCourses::ChildContentTag.where(content: self).take own_tag&.child_subscription&.create_content_tag_for!(old_assignment, :downstream_changes => ['workflow_state']) end - elsif self.assignment && @saved_by != :assignment && !self.root_topic_id - deleted_assignment = self.assignment.deleted? - self.sync_assignment - self.assignment.workflow_state = "published" if is_announcement && deleted_assignment - self.assignment.description = self.message + elsif assignment && @saved_by != :assignment && !root_topic_id + deleted_assignment = assignment.deleted? + sync_assignment + assignment.workflow_state = "published" if is_announcement && deleted_assignment + assignment.description = message if saved_change_to_group_category_id? - self.assignment.validate_assignment_overrides(force_override_destroy: true) + assignment.validate_assignment_overrides(force_override_destroy: true) end - self.assignment.save + assignment.save end # make sure that if the topic has a new assignment (either by going from # ungraded to graded, or from one assignment to another; we ignore the # transition from graded to ungraded) we acknowledge that the users that # have posted have contributed to the topic - if self.assignment_id && self.saved_change_to_assignment_id? + if assignment_id && saved_change_to_assignment_id? recalculate_context_module_actions! end end protected :update_assignment def recalculate_context_module_actions! - posters.each { |user| self.context_module_action(user, :contributed) } + posters.each { |user| context_module_action(user, :contributed) } end def is_announcement @@ -370,12 +370,12 @@ def homeroom_announcement?(_context) end def root_topic? - !self.root_topic_id && self.has_group_category? + !root_topic_id && has_group_category? end # only the root level entries def discussion_subentries - self.root_discussion_entries + root_discussion_entries end # count of all active discussion_entries @@ -384,7 +384,7 @@ def discussion_subentry_count end def for_group_discussion? - self.has_group_category? && self.root_topic? + has_group_category? && root_topic? end def plaintext_message=(val) @@ -392,11 +392,11 @@ def plaintext_message=(val) end def plaintext_message - truncate_html(self.message, :max_length => 250) + truncate_html(message, :max_length => 250) end def create_participant - self.discussion_topic_participants.create(:user => self.user, :workflow_state => "read", :unread_entry_count => 0, :subscribed => !subscription_hold(self.user, nil)) if self.user + discussion_topic_participants.create(:user => user, :workflow_state => "read", :unread_entry_count => 0, :subscribed => !subscription_hold(user, nil)) if user end def update_materialized_view @@ -407,11 +407,11 @@ def update_materialized_view end def group_category_deleted_with_entries? - self.group_category.try(:deleted_at?) && !can_group? + group_category.try(:deleted_at?) && !can_group? end def get_potentially_conflicting_titles(title_base) - DiscussionTopic.active.where(context_type: self.context_type, context_id: self.context_id) + DiscussionTopic.active.where(context_type: context_type, context_id: context_id) .starting_with_title(title_base).pluck("title").to_set end @@ -419,28 +419,28 @@ def get_potentially_conflicting_titles(title_base) def duplicate_base_model(title, opts) DiscussionTopic.new({ :title => title, - :message => self.message, - :context_id => self.context_id, - :context_type => self.context_type, - :user_id => opts[:user] ? opts[:user].id : self.user_id, - :type => self.type, + :message => message, + :context_id => context_id, + :context_type => context_type, + :user_id => opts[:user] ? opts[:user].id : user_id, + :type => type, :workflow_state => "unpublished", - :could_be_locked => self.could_be_locked, - :context_code => self.context_code, - :podcast_enabled => self.podcast_enabled, - :require_initial_post => self.require_initial_post, - :podcast_has_student_posts => self.podcast_has_student_posts, - :discussion_type => self.discussion_type, - :delayed_post_at => self.delayed_post_at, - :lock_at => self.lock_at, - :pinned => self.pinned, - :locked => self.locked, - :group_category_id => self.group_category_id, - :allow_rating => self.allow_rating, - :only_graders_can_rate => self.only_graders_can_rate, - :sort_by_rating => self.sort_by_rating, - :todo_date => self.todo_date, - :is_section_specific => self.is_section_specific + :could_be_locked => could_be_locked, + :context_code => context_code, + :podcast_enabled => podcast_enabled, + :require_initial_post => require_initial_post, + :podcast_has_student_posts => podcast_has_student_posts, + :discussion_type => discussion_type, + :delayed_post_at => delayed_post_at, + :lock_at => lock_at, + :pinned => pinned, + :locked => locked, + :group_category_id => group_category_id, + :allow_rating => allow_rating, + :only_graders_can_rate => only_graders_can_rate, + :sort_by_rating => sort_by_rating, + :todo_date => todo_date, + :is_section_specific => is_section_specific }) end @@ -448,7 +448,7 @@ def duplicate_base_model(title, opts) # Does not duplicate the child topics; the hooks take care of that for us. def duplicate(opts = {}) # Don't clone a new record - return self if self.new_record? + return self if new_record? default_opts = { :duplicate_assignment => true, @@ -457,27 +457,27 @@ def duplicate(opts = {}) } opts_with_default = default_opts.merge(opts) copy_title = - opts_with_default[:copy_title] || get_copy_title(self, t("Copy"), self.title) - result = self.duplicate_base_model(copy_title, opts_with_default) + opts_with_default[:copy_title] || get_copy_title(self, t("Copy"), title) + result = duplicate_base_model(copy_title, opts_with_default) # Start with a position guaranteed to not conflict with existing ones. # Clients are encouraged to set the correct position later on and do # an insert_at upon save. - if self.pinned - result.position = self.context.discussion_topics.active.where(:pinned => true).maximum(:position) + 1 + if pinned + result.position = context.discussion_topics.active.where(:pinned => true).maximum(:position) + 1 end - if self.assignment && opts_with_default[:duplicate_assignment] - result.assignment = self.assignment.duplicate({ - :duplicate_discussion_topic => false, - :copy_title => result.title - }) + if assignment && opts_with_default[:duplicate_assignment] + result.assignment = assignment.duplicate({ + :duplicate_discussion_topic => false, + :copy_title => result.title + }) end result.discussion_topic_section_visibilities = [] - if self.is_section_specific - original_visibilities = self.discussion_topic_section_visibilities.active + if is_section_specific + original_visibilities = discussion_topic_section_visibilities.active original_visibilities.each do |visibility| new_visibility = DiscussionTopicSectionVisibility.new( :discussion_topic => result, @@ -522,12 +522,12 @@ def change_read_state(new_state, current_user = nil) current_user ||= self.current_user return nil unless current_user - self.context_module_action(current_user, :read) if new_state == 'read' + context_module_action(current_user, :read) if new_state == 'read' - return true if new_state == self.read_state(current_user) + return true if new_state == read_state(current_user) StreamItem.update_read_state_for_asset(self, new_state, current_user.id) - self.update_or_create_participant(:current_user => current_user, :new_state => new_state) + update_or_create_participant(:current_user => current_user, :new_state => new_state) end def change_all_read_state(new_state, current_user = nil, opts = {}) @@ -544,7 +544,7 @@ def change_all_read_state(new_state, current_user = nil, opts = {}) end def update_stream_item_state(current_user, new_state) - self.context_module_action(current_user, :read) if new_state == 'read' + context_module_action(current_user, :read) if new_state == 'read' StreamItem.update_read_state_for_asset(self, new_state, current_user.id) end protected :update_stream_item_state @@ -565,12 +565,12 @@ def update_participants_read_state(current_user, new_state, update_fields) update_or_create_participant(current_user: current_user, new_state: new_state, - new_count: new_state == 'unread' ? self.default_unread_count : 0) + new_count: new_state == 'unread' ? default_unread_count : 0) end protected :update_participants_read_state def default_unread_count - self.discussion_entries.active.count + discussion_entries.active.count end # Do not use the lock options unless you truly need @@ -582,12 +582,12 @@ def unread_count(current_user = nil, lock: false, opts: {}) environment = lock ? :primary : :secondary GuardRail.activate(environment) do - topic_participant = if opts[:use_preload] && self.association(:discussion_topic_participants).loaded? - self.discussion_topic_participants.find { |dtp| dtp.user_id == current_user.id } + topic_participant = if opts[:use_preload] && association(:discussion_topic_participants).loaded? + discussion_topic_participants.find { |dtp| dtp.user_id == current_user.id } else discussion_topic_participants.where(user_id: current_user).select(:unread_entry_count).lock(lock).take end - topic_participant&.unread_entry_count || self.default_unread_count + topic_participant&.unread_entry_count || default_unread_count end end @@ -616,8 +616,8 @@ def subscribed?(current_user = nil, opts: {}) participant = DiscussionTopicParticipant.where(user_id: current_user.id, discussion_topic_id: child_topics.pluck(:id)).take end - participant ||= if opts[:use_preload] && self.association(:discussion_topic_participants).loaded? - self.discussion_topic_participants.find { |dtp| dtp.user_id == current_user.id } + participant ||= if opts[:use_preload] && association(:discussion_topic_participants).loaded? + discussion_topic_participants.find { |dtp| dtp.user_id == current_user.id } else discussion_topic_participants.where(user_id: current_user).take end @@ -680,11 +680,11 @@ def update_or_create_participant(opts = {}) GuardRail.activate(:primary) do DiscussionTopic.uncached do DiscussionTopic.unique_constraint_retry do - topic_participant = self.discussion_topic_participants.where(:user_id => current_user).lock.first - topic_participant ||= self.discussion_topic_participants.build(:user => current_user, - :unread_entry_count => self.unread_count(current_user, lock: true), - :workflow_state => "unread", - :subscribed => current_user == user && !subscription_hold(current_user, nil)) + topic_participant = discussion_topic_participants.where(:user_id => current_user).lock.first + topic_participant ||= discussion_topic_participants.build(:user => current_user, + :unread_entry_count => unread_count(current_user, lock: true), + :workflow_state => "unread", + :subscribed => current_user == user && !subscription_hold(current_user, nil)) topic_participant.workflow_state = opts[:new_state] if opts[:new_state] topic_participant.unread_entry_count += opts[:offset] if opts[:offset] && opts[:offset] != 0 topic_participant.unread_entry_count = opts[:new_count] if opts[:new_count] @@ -803,14 +803,14 @@ def initialize(message = nil, status_code = nil) def should_lock_yet # not assignment or vdd aware! only use this to check the topic's own field! # you should be checking other lock statuses in addition to this one - self.lock_at && self.lock_at < Time.now.utc + lock_at && lock_at < Time.now.utc end alias_method :not_available_anymore?, :should_lock_yet def should_not_post_yet # not assignment or vdd aware! only use this to check the topic's own field! # you should be checking other lock statuses in addition to this one - self.delayed_post_at && self.delayed_post_at > Time.now.utc + delayed_post_at && delayed_post_at > Time.now.utc end alias_method :not_available_yet?, :should_not_post_yet @@ -843,7 +843,7 @@ def update_based_on_date(for_blueprint: false) def active? # using state instead of workflow_state so this works with new records - self.state == :active || (!self.is_announcement && self.state == :post_delayed) + state == :active || (!is_announcement && state == :post_delayed) end def publish @@ -867,13 +867,13 @@ def unpublish! end def can_lock? - !(self.assignment.try(:due_at) && self.assignment.due_at > Time.now) + !(assignment.try(:due_at) && assignment.due_at > Time.now) end def comments_disabled? - !!(self.is_a?(Announcement) && - self.context.is_a?(Course) && - self.context.lock_all_announcements) + !!(is_a?(Announcement) && + context.is_a?(Course) && + context.lock_all_announcements) end def lock(opts = {}) @@ -886,7 +886,7 @@ def lock(opts = {}) def unlock(opts = {}) self.locked = false - self.workflow_state = 'active' if self.workflow_state == 'locked' + self.workflow_state = 'active' if workflow_state == 'locked' save! unless opts[:without_save] end alias_method :unlock!, :unlock @@ -901,14 +901,14 @@ def published? def can_unpublish?(opts = {}) return @can_unpublish unless @can_unpublish.nil? - @can_unpublish = if self.assignment - !self.assignment.has_student_submissions? + @can_unpublish = if assignment + !assignment.has_student_submissions? else - student_ids = opts[:student_ids] || self.context.all_real_student_enrollments.select(:user_id) - if self.for_group_discussion? + student_ids = opts[:student_ids] || context.all_real_student_enrollments.select(:user_id) + if for_group_discussion? !DiscussionEntry.active.joins(:discussion_topic).merge(child_topics).where(user_id: student_ids).exists? else - !self.discussion_entries.active.where(:user_id => student_ids).exists? + !discussion_entries.active.where(:user_id => student_ids).exists? end end end @@ -939,17 +939,17 @@ def can_group?(opts = {}) end def should_send_to_stream - self.published? && - !self.not_available_yet? && - !self.cloned_item_id && - !(self.root_topic_id && self.has_group_category?) && - !self.in_unpublished_module? && - !self.locked_by_module? + published? && + !not_available_yet? && + !cloned_item_id && + !(root_topic_id && has_group_category?) && + !in_unpublished_module? && + !locked_by_module? end on_create_send_to_streams do if should_send_to_stream - self.active_participants_with_visibility + active_participants_with_visibility end end @@ -957,7 +957,7 @@ def should_send_to_stream check_state = !is_announcement ? 'unpublished' : 'post_delayed' became_active = workflow_state_before_last_save == check_state && workflow_state == 'active' if should_send_to_stream && (@content_changed || became_active) - self.active_participants_with_visibility + active_participants_with_visibility end end @@ -975,21 +975,21 @@ def in_unpublished_module? end def locked_by_module? - return false unless self.context_module_tags.any? + return false unless context_module_tags.any? ContentTag.where(content_type: "DiscussionTopic", content_id: self, workflow_state: "active").all? { |tag| tag.context_module.unlock_at&.future? } end def should_clear_all_stream_items? - (!self.published? && self.saved_change_to_attribute?(:workflow_state)) || - (self.is_announcement && self.not_available_yet? && self.saved_change_to_attribute?(:delayed_post_at)) + (!published? && saved_change_to_attribute?(:workflow_state)) || + (is_announcement && not_available_yet? && saved_change_to_attribute?(:delayed_post_at)) end def clear_non_applicable_stream_items - return self.clear_stream_items if should_clear_all_stream_items? + return clear_stream_items if should_clear_all_stream_items? - section = self.is_section_specific? ? @sections_changed : self.is_section_specific_before_last_save - lock = self.locked_by_module? + section = is_section_specific? ? @sections_changed : is_section_specific_before_last_save + lock = locked_by_module? if lock || section delay_if_production.partially_clear_stream_items(locked_by_module: lock, section_specific: section) @@ -1000,12 +1000,12 @@ def partially_clear_stream_items(locked_by_module: false, section_specific: fals remaining_participants = participants if section_specific user_ids = [] stream_item&.stream_item_instances&.shard(stream_item)&.find_each do |item| - if (locked_by_module && self.locked_by_module_item?(item.user)) || + if (locked_by_module && locked_by_module_item?(item.user)) || (section_specific && remaining_participants.none? { |p| p.id == item.user_id }) destroy_item_and_track(item, user_ids) end end - self.clear_stream_item_cache_for(user_ids) + clear_stream_item_cache_for(user_ids) end def destroy_item_and_track(item, user_ids) @@ -1025,26 +1025,26 @@ def clear_stream_item_cache_for(user_ids) end def require_initial_post? - self.require_initial_post || self.root_topic&.require_initial_post + require_initial_post || root_topic&.require_initial_post end def user_ids_who_have_posted_and_admins scope = DiscussionEntry.active.select(:user_id).distinct.where(:discussion_topic_id => self) ids = scope.pluck(:user_id) - ids += self.course.admin_enrollments.active.pluck(:user_id) if self.course.is_a?(Course) + ids += course.admin_enrollments.active.pluck(:user_id) if course.is_a?(Course) ids end def user_can_see_posts?(user, session = nil, associated_user_ids = []) return false unless user - !self.require_initial_post? || self.grants_right?(user, session, :read_as_admin) || + !require_initial_post? || grants_right?(user, session, :read_as_admin) || (([user.id] + associated_user_ids) & user_ids_who_have_posted_and_admins).any? end def reply_from(opts) - raise IncomingMail::Errors::ReplyToDeletedDiscussion if self.deleted? - raise IncomingMail::Errors::UnknownAddress if self.context.root_account.deleted? + raise IncomingMail::Errors::ReplyToDeletedDiscussion if deleted? + raise IncomingMail::Errors::UnknownAddress if context.root_account.deleted? user = opts[:user] if opts[:html] @@ -1053,13 +1053,13 @@ def reply_from(opts) message = opts[:text].strip message = format_message(message).first end - user = nil unless user && self.context.users.include?(user) + user = nil unless user && context.users.include?(user) if !user raise IncomingMail::Errors::InvalidParticipant - elsif !self.grants_right?(user, :read) + elsif !grants_right?(user, :read) nil else - self.shard.activate do + shard.activate do entry = discussion_entries.new(message: message, user: user) if !entry.grants_right?(user, :create) raise IncomingMail::Errors::ReplyToLockedTopic @@ -1076,42 +1076,42 @@ def destroy ContentTag.delete_for(self) self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - self.discussion_topic_section_visibilities&.update_all(:workflow_state => "deleted") - self.save + discussion_topic_section_visibilities&.update_all(:workflow_state => "deleted") + save - if self.for_assignment? && self.root_topic_id.blank? - self.assignment.destroy unless self.assignment.deleted? + if for_assignment? && root_topic_id.blank? + assignment.destroy unless assignment.deleted? end - self.child_topics.each(&:destroy) + child_topics.each(&:destroy) end def restore(from = nil) - if self.is_section_specific? - DiscussionTopicSectionVisibility.where(discussion_topic_id: self.id).to_a.uniq(&:course_section_id).each do |dtsv| + if is_section_specific? + DiscussionTopicSectionVisibility.where(discussion_topic_id: id).to_a.uniq(&:course_section_id).each do |dtsv| dtsv.workflow_state = 'active' dtsv.save end end self.workflow_state = can_unpublish? ? 'unpublished' : 'active' - self.save + save - if from != :assignment && self.for_assignment? && self.root_topic_id.blank? - self.assignment.restore(:discussion_topic) + if from != :assignment && for_assignment? && root_topic_id.blank? + assignment.restore(:discussion_topic) end - self.child_topics.each(&:restore) + child_topics.each(&:restore) end def unlink!(type) @saved_by = type self.assignment = nil - if self.discussion_entries.empty? - self.destroy + if discussion_entries.empty? + destroy else - self.save + save end - self.child_topics.each { |t| t.unlink!(:assignment) } + child_topics.each { |t| t.unlink!(:assignment) } end def self.per_page @@ -1119,7 +1119,7 @@ def self.per_page end def initialize_last_reply_at - unless [:migration, :after_migration].include?(self.saved_by) + unless [:migration, :after_migration].include?(saved_by) self.posted_at ||= Time.now.utc self.last_reply_at ||= Time.now.utc end @@ -1128,24 +1128,24 @@ def initialize_last_reply_at set_policy do # Users may have can :read, but should not have access to all the data # because the topic is locked_for?(user) - given { |user| self.visible_for?(user) } + given { |user| visible_for?(user) } can :read - given { |user| self.grants_right?(user, :read) } + given { |user| grants_right?(user, :read) } can :read_replies - given { |user| self.user && self.user == user && self.visible_for?(user) && !self.locked_for?(user, :check_policies => true) && can_participate_in_course?(user) } + given { |user| self.user && self.user == user && visible_for?(user) && !locked_for?(user, :check_policies => true) && can_participate_in_course?(user) } can :reply - given { |user| self.user && self.user == user && self.available_for?(user) && context.user_can_manage_own_discussion_posts?(user) && context.grants_right?(user, :participate_as_student) } + given { |user| self.user && self.user == user && available_for?(user) && context.user_can_manage_own_discussion_posts?(user) && context.grants_right?(user, :participate_as_student) } can :update - given { |user| self.user && self.user == user and self.discussion_entries.active.empty? && self.available_for?(user) && !self.root_topic_id && context.user_can_manage_own_discussion_posts?(user) && context.grants_right?(user, :participate_as_student) } + given { |user| self.user && self.user == user and discussion_entries.active.empty? && available_for?(user) && !root_topic_id && context.user_can_manage_own_discussion_posts?(user) && context.grants_right?(user, :participate_as_student) } can :delete given { |user, session| - !self.locked_for?(user, :check_policies => true) && - self.context.grants_right?(user, session, :post_to_forum) && self.visible_for?(user) && can_participate_in_course?(user) + !locked_for?(user, :check_policies => true) && + context.grants_right?(user, session, :post_to_forum) && visible_for?(user) && can_participate_in_course?(user) } can :reply @@ -1161,28 +1161,28 @@ def initialize_last_reply_at given { course.student_reporting? } can :student_reporting - given { |user, session| !self.root_topic_id && self.context.grants_all_rights?(user, session, :read_forum, :moderate_forum) && self.available_for?(user) } + given { |user, session| !root_topic_id && context.grants_all_rights?(user, session, :read_forum, :moderate_forum) && available_for?(user) } can :update and can :read_as_admin and can :delete and can :create and can :read and can :attach # Moderators can still modify content even in unavailable topics (*especially* unlocking them), but can't create new content - given { |user, session| !self.root_topic_id && self.context.grants_all_rights?(user, session, :read_forum, :moderate_forum) } + given { |user, session| !root_topic_id && context.grants_all_rights?(user, session, :read_forum, :moderate_forum) } can :update and can :read_as_admin and can :delete and can :read and can :attach - given { |user, session| self.root_topic&.grants_right?(user, session, :read_as_admin) } + given { |user, session| root_topic&.grants_right?(user, session, :read_as_admin) } can :read_as_admin - given { |user, session| self.root_topic&.grants_right?(user, session, :delete) } + given { |user, session| root_topic&.grants_right?(user, session, :delete) } can :delete - given { |user, session| self.root_topic&.grants_right?(user, session, :read) } + given { |user, session| root_topic&.grants_right?(user, session, :read) } can :read - given { |user, session| self.context.grants_all_rights?(user, session, :moderate_forum, :read_forum) } + given { |user, session| context.grants_all_rights?(user, session, :moderate_forum, :read_forum) } can :moderate_forum given do |user, session| - self.allow_rating && (!self.only_graders_can_rate || - self.course.grants_right?(user, session, :manage_grades)) + allow_rating && (!only_graders_can_rate || + course.grants_right?(user, session, :manage_grades)) end can :rate end @@ -1205,13 +1205,13 @@ def user_can_create(user, session) end def user_can_duplicate(user, session) - self.context.is_a?(Group) || - self.course.user_is_instructor?(user) || + context.is_a?(Group) || + course.user_is_instructor?(user) || context.grants_right?(user, session, :read_as_admin) end def discussion_topic_id - self.id + id end def discussion_topic @@ -1219,18 +1219,18 @@ def discussion_topic end def to_atom(opts = {}) - author_name = self.user.present? ? self.user.name : t('#discussion_topic.atom_no_author', "No Author") - prefix = [self.is_announcement ? t('#titles.announcement', "Announcement") : t('#titles.discussion', "Discussion")] - prefix << self.context.name if opts[:include_context] + author_name = user.present? ? user.name : t('#discussion_topic.atom_no_author', "No Author") + prefix = [is_announcement ? t('#titles.announcement', "Announcement") : t('#titles.discussion', "Discussion")] + prefix << context.name if opts[:include_context] Atom::Entry.new do |entry| - entry.title = [before_label(prefix.to_sentence), self.title].join(" ") + entry.title = [before_label(prefix.to_sentence), title].join(" ") entry.authors << Atom::Person.new(:name => author_name) - entry.updated = self.updated_at - entry.published = self.created_at - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime("%Y-%m-%d")}:/discussion_topics/#{self.feed_code}" + entry.updated = updated_at + entry.published = created_at + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime("%Y-%m-%d")}:/discussion_topics/#{feed_code}" entry.links << Atom::Link.new(:rel => 'alternate', - :href => "http://#{HostUrl.context_host(self.context)}/#{context_url_prefix}/discussion_topics/#{self.id}") - entry.content = Atom::Content::Html.new(self.message || "") + :href => "http://#{HostUrl.context_host(context)}/#{context_url_prefix}/discussion_topics/#{id}") + entry.content = Atom::Content::Html.new(message || "") end end @@ -1239,14 +1239,14 @@ def context_prefix end def context_module_action(user, action, points = nil) - return self.root_topic.context_module_action(user, action, points) if self.root_topic + return root_topic.context_module_action(user, action, points) if root_topic - tags_to_update = self.context_module_tags.to_a - if self.for_assignment? - tags_to_update += self.assignment.context_module_tags + tags_to_update = context_module_tags.to_a + if for_assignment? + tags_to_update += assignment.context_module_tags if context.grants_right?(user, :participate_as_student) && assignment.visible_to_user?(user) && [:contributed, :deleted].include?(action) only_update = (action == :deleted) # if we're deleting an entry, don't make a submission if it wasn't there already - self.ensure_submission(user, only_update) + ensure_submission(user, only_update) end end unless action == :deleted @@ -1255,12 +1255,12 @@ def context_module_action(user, action, points = nil) end def ensure_submission(user, only_update = false) - topic = (self.root_topic? && self.child_topic_for(user)) || self + topic = (root_topic? && child_topic_for(user)) || self - submission = Submission.active.where(assignment_id: self.assignment_id, user_id: user).first + submission = Submission.active.where(assignment_id: assignment_id, user_id: user).first unless only_update || (submission && submission.submission_type == 'discussion_topic' && submission.workflow_state != 'unsubmitted') - submission = self.assignment.submit_homework(user, :submission_type => 'discussion_topic', - :submitted_at => topic && topic.discussion_entries.active.where(:user_id => user).minimum(:created_at)) + submission = assignment.submit_homework(user, :submission_type => 'discussion_topic', + :submitted_at => topic && topic.discussion_entries.active.where(:user_id => user).minimum(:created_at)) end return unless submission @@ -1273,10 +1273,10 @@ def ensure_submission(user, only_update = false) def send_notification_for_context? notification_context = - if self.context.is_a?(Group) && self.context.context.is_a?(Course) - self.context.context # we need to go deeper + if context.is_a?(Group) && context.context.is_a?(Course) + context.context # we need to go deeper else - self.context + context end notification_context.available? end @@ -1305,64 +1305,64 @@ def set_assignment=(val); end # of the topic. If the topic is not section specific this just returns the # original list. def users_with_section_visibility(users) - return users unless self.is_section_specific? && self.context.is_a?(Course) + return users unless is_section_specific? && context.is_a?(Course) non_nil_users = users.compact - section_ids = DiscussionTopicSectionVisibility.active.where(:discussion_topic_id => self.id) + section_ids = DiscussionTopicSectionVisibility.active.where(:discussion_topic_id => id) .pluck(:course_section_id) user_ids = non_nil_users.pluck(:id) # Context is known to be a course here - users_in_sections = self.context.enrollments.active - .where(:user_id => user_ids, :course_section_id => section_ids).pluck(:user_id).to_set - unlocked_teachers = self.context.enrollments.active.instructor - .where(:limit_privileges_to_course_section => false, :user_id => user_ids) - .pluck(:user_id).to_set + users_in_sections = context.enrollments.active + .where(:user_id => user_ids, :course_section_id => section_ids).pluck(:user_id).to_set + unlocked_teachers = context.enrollments.active.instructor + .where(:limit_privileges_to_course_section => false, :user_id => user_ids) + .pluck(:user_id).to_set permitted_user_ids = users_in_sections.union(unlocked_teachers) non_nil_users.select { |u| permitted_user_ids.include?(u.id) } end def participants(include_observers = false) participants = context.participants(include_observers: include_observers, by_date: true) - participants_in_section = self.users_with_section_visibility(participants.compact) - if self.user && !participants_in_section.map(&:id).to_set.include?(self.user.id) - participants_in_section += [self.user] + participants_in_section = users_with_section_visibility(participants.compact) + if user && !participants_in_section.map(&:id).to_set.include?(user.id) + participants_in_section += [user] end participants_in_section end def visible_to_admins_only? - (self.context.respond_to?(:available?) && !self.context.available?) || + (context.respond_to?(:available?) && !context.available?) || unpublished? || not_available_yet? || not_available_anymore? end def active_participants(include_observers = false) - if visible_to_admins_only? && self.context.respond_to?(:participating_admins) - self.context.participating_admins + if visible_to_admins_only? && context.respond_to?(:participating_admins) + context.participating_admins else - self.participants(include_observers) + participants(include_observers) end end def active_participants_include_tas_and_teachers(include_observers = false) participants = active_participants(include_observers) - if self.context.is_a?(Group) && !self.context.course.nil? - participants += self.context.course.participating_instructors_by_date + if context.is_a?(Group) && !context.course.nil? + participants += context.course.participating_instructors_by_date participants = participants.compact.uniq end participants end def users_with_permissions(users) - permission = self.is_announcement ? :read_announcements : :read_forum + permission = is_announcement ? :read_announcements : :read_forum course = self.course unless course.is_a?(Course) return users.select do |u| - self.is_announcement ? self.context.grants_right?(u, :read_announcements) : self.context.grants_right?(u, :read_forum) + is_announcement ? context.grants_right?(u, :read_announcements) : context.grants_right?(u, :read_forum) end end readers = self.course.filter_users_by_permission(users, permission) - self.users_with_section_visibility(readers) + users_with_section_visibility(readers) end def course @@ -1374,9 +1374,9 @@ def group end def active_participants_with_visibility - return active_participants unless self.for_assignment? + return active_participants unless for_assignment? - users_with_visibility = self.assignment.students_with_visibility.pluck(:id) + users_with_visibility = assignment.students_with_visibility.pluck(:id) admin_ids = course.participating_admins.pluck(:id) users_with_visibility.concat(admin_ids) @@ -1404,8 +1404,8 @@ def subscribers end def filter_message_users(users) - if self.for_assignment? - students_with_visibility = self.assignment.students_with_visibility.pluck(:id) + if for_assignment? + students_with_visibility = assignment.students_with_visibility.pluck(:id) admin_ids = course.participating_admins.pluck(:id) observer_ids = course.participating_observers.pluck(:id) @@ -1421,19 +1421,19 @@ def filter_message_users(users) end def posters - user_ids = discussion_entries.map(&:user_id).push(self.user_id).uniq + user_ids = discussion_entries.map(&:user_id).push(user_id).uniq participating_users(user_ids) end def user_name - self.user ? self.user.name : nil + user ? user.name : nil end def available_from_for(user) - if self.assignment - self.assignment.overridden_for(user).unlock_at + if assignment + assignment.overridden_for(user).unlock_at else - self.available_from + available_from end end @@ -1452,18 +1452,18 @@ def available_for?(user, opts = {}) def visible_for?(user = nil) RequestCache.cache('discussion_visible_for', self, is_announcement, user) do # user is the topic's author - next true if user && user.id == self.user_id + next true if user && user.id == user_id next false unless context next false unless is_announcement ? context.grants_right?(user, :read_announcements) : context.grants_right?(user, :read_forum) # Don't have visibilites for any of the specific sections in a section specific topic - if context.is_a?(Course) && self.try(:is_section_specific) + if context.is_a?(Course) && try(:is_section_specific) section_visibilities = context.course_section_visibility(user) next false if section_visibilities == :none if section_visibilities != :all - course_specific_sections = self.course_sections.pluck(:id) + course_specific_sections = course_sections.pluck(:id) next false if (section_visibilities & course_specific_sections).empty? end end @@ -1473,7 +1473,7 @@ def visible_for?(user = nil) next true if context.grants_any_right?(user, :manage, :read_course_content) # assignment exists and isn't assigned to user (differentiated assignments) - if for_assignment? && !self.assignment.visible_to_user?(user) + if for_assignment? && !assignment.visible_to_user?(user) next false end @@ -1491,11 +1491,11 @@ def visible_for?(user = nil) end def can_participate_in_course?(user) - if self.group&.deleted? + if group&.deleted? false - elsif self.course.is_a?(Course) + elsif course.is_a?(Course) # this probably isn't a perfect way to determine this but I can't think of a better one - self.course.enrollments.for_user(user).active_by_date.exists? || self.course.grants_right?(user, :read_as_admin) + course.enrollments.for_user(user).active_by_date.exists? || course.grants_right?(user, :read_as_admin) else true end @@ -1508,19 +1508,19 @@ def can_participate_in_course?(user) # Generally you want to call :locked_for?(user, check_policies: true), which # will call this method. def low_level_locked_for?(user, opts = {}) - return false if opts[:check_policies] && self.grants_right?(user, :read_as_admin) + return false if opts[:check_policies] && grants_right?(user, :read_as_admin) RequestCache.cache(locked_request_cache_key(user)) do locked = false - if self.delayed_post_at && self.delayed_post_at > Time.now + if delayed_post_at && delayed_post_at > Time.now locked = { object: self, unlock_at: delayed_post_at } - elsif self.lock_at && self.lock_at < Time.now + elsif lock_at && lock_at < Time.now locked = { object: self, lock_at: lock_at, can_view: true } elsif !opts[:skip_assignment] && (l = assignment&.low_level_locked_for?(user, opts)) locked = l - elsif self.could_be_locked && (item = locked_by_module_item?(user, opts)) + elsif could_be_locked && (item = locked_by_module_item?(user, opts)) locked = { object: self, module: item.context_module } - elsif self.locked? # nothing more specific, it's just locked + elsif locked? # nothing more specific, it's just locked locked = { object: self, can_view: true } elsif (l = root_topic&.low_level_locked_for?(user, opts)) # rubocop:disable Lint/DuplicateBranch locked = l @@ -1644,7 +1644,7 @@ def self.to_podcast(elements) def initial_post_required?(user, session = nil) if require_initial_post? - associated_user_ids = user.observer_enrollments.active.where(course_id: self.course).pluck(:associated_user_id).compact + associated_user_ids = user.observer_enrollments.active.where(course_id: course).pluck(:associated_user_id).compact return !user_can_see_posts?(user, session, associated_user_ids) end false @@ -1664,7 +1664,7 @@ def initial_post_required?(user, session = nil) # where we're creating topics on the first write - until that first write, we need to return # blank data on reads. def materialized_view(opts = {}) - if self.new_record? + if new_record? ["[]", [], [], []] else DiscussionTopic::MaterializedView.materialized_view_for(self, opts) @@ -1687,6 +1687,6 @@ def grading_standard_or_default end def set_root_account_id - self.root_account_id ||= self.context&.root_account_id + self.root_account_id ||= context&.root_account_id end end diff --git a/app/models/discussion_topic/materialized_view.rb b/app/models/discussion_topic/materialized_view.rb index edc4bd3024665..e6f966b0264f0 100644 --- a/app/models/discussion_topic/materialized_view.rb +++ b/app/models/discussion_topic/materialized_view.rb @@ -43,13 +43,13 @@ def self.for(discussion_topic) discussion_topic.shard.activate do # first try to pull the view from the secondary. we can't just do this in the # unique_constraint_retry since it begins a transaction. - view = GuardRail.activate(:secondary) { self.where(discussion_topic_id: discussion_topic).first } + view = GuardRail.activate(:secondary) { where(discussion_topic_id: discussion_topic).first } unless view # if the view wasn't found, drop into the unique_constraint_retry # transaction loop on master. unique_constraint_retry do - view = self.where(discussion_topic_id: discussion_topic).first || - self.create!(:discussion_topic => discussion_topic) + view = where(discussion_topic_id: discussion_topic).first || + create!(:discussion_topic => discussion_topic) end end view @@ -66,26 +66,26 @@ def up_to_date? end def all_entries - if self.discussion_topic.sort_by_rating - self.discussion_topic.rated_discussion_entries + if discussion_topic.sort_by_rating + discussion_topic.rated_discussion_entries else - self.discussion_topic.discussion_entries + discussion_topic.discussion_entries end end def relativize_ids(ids) - if self.shard.id == Shard.current.id + if shard.id == Shard.current.id ids else - ids.map { |id| Shard.relative_id_for(id, self.shard, Shard.current) } + ids.map { |id| Shard.relative_id_for(id, shard, Shard.current) } end end def recursively_relativize_json_ids(data) data.map do |entry| - entry["id"] = Shard.relative_id_for(entry["id"], self.shard, Shard.current).to_s + entry["id"] = Shard.relative_id_for(entry["id"], shard, Shard.current).to_s if entry.key? "user_id" - entry["user_id"] = Shard.relative_id_for(entry["user_id"], self.shard, Shard.current).to_s + entry["user_id"] = Shard.relative_id_for(entry["user_id"], shard, Shard.current).to_s end if entry["replies"] entry["replies"] = recursively_relativize_json_ids(entry["replies"]) @@ -95,10 +95,10 @@ def recursively_relativize_json_ids(data) end def relativize_json_structure_ids - if self.shard.id == Shard.current.id - self.json_structure + if shard.id == Shard.current.id + json_structure else - data = JSON.parse(self.json_structure) + data = JSON.parse(json_structure) relativized = recursively_relativize_json_ids(data) JSON.dump(relativized) end @@ -117,10 +117,10 @@ def materialized_view_json(opts = {}) update_materialized_view(xlog_location: self.class.current_xlog_location) end - if self.json_structure.present? + if json_structure.present? json_structure = relativize_json_structure_ids - participant_ids = relativize_ids(self.participants_array) - entry_ids = relativize_ids(self.entry_ids_array) + participant_ids = relativize_ids(participants_array) + entry_ids = relativize_ids(entry_ids_array) if opts[:include_new_entries] @for_mobile = true if opts[:include_mobile_overrides] @@ -145,18 +145,18 @@ def update_materialized_view(xlog_location: nil, use_master: false) unless self.class.wait_for_replication(start: xlog_location, timeout: timeout) # failed to replicate - requeue later run_at = Setting.get("discussion_materialized_view_replication_failure_retry", "300").to_i.seconds.from_now - delay(singleton: "materialized_discussion:#{Shard.birth.activate { self.discussion_topic_id }}", run_at: run_at) + delay(singleton: "materialized_discussion:#{Shard.birth.activate { discussion_topic_id }}", run_at: run_at) .update_materialized_view(synchronous: true, xlog_location: xlog_location, use_master: use_master) raise ReplicationTimeoutError, "timed out waiting for replication" end end self.generation_started_at = Time.zone.now view_json, user_ids, entry_lookup = - self.build_materialized_view(use_master: use_master) + build_materialized_view(use_master: use_master) self.json_structure = view_json self.participants_array = user_ids self.entry_ids_array = entry_lookup - self.save! + save! rescue ReplicationTimeoutError => e Canvas::Errors.capture_exception(:discussion_materialization, e, :warn) raise Delayed::RetriableError, e.message diff --git a/app/models/discussion_topic_participant.rb b/app/models/discussion_topic_participant.rb index 6ed8249175dcc..2ff7d4c169ac4 100644 --- a/app/models/discussion_topic_participant.rb +++ b/app/models/discussion_topic_participant.rb @@ -54,6 +54,6 @@ def check_planner_cache end def set_root_account_id - self.root_account_id = self.discussion_topic.root_account_id + self.root_account_id = discussion_topic.root_account_id end end diff --git a/app/models/discussion_topic_section_visibility.rb b/app/models/discussion_topic_section_visibility.rb index 335c034e2352c..446cf35ea81bc 100644 --- a/app/models/discussion_topic_section_visibility.rb +++ b/app/models/discussion_topic_section_visibility.rb @@ -41,28 +41,28 @@ class DiscussionTopicSectionVisibility < ActiveRecord::Base alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.save! + save! end def discussion_topic_is_section_specific - return true if self.deleted? || self.discussion_topic.is_section_specific + return true if deleted? || discussion_topic.is_section_specific - self.errors.add(:discussion_topic_id, t("Cannot add section to a non-section-specific discussion")) + errors.add(:discussion_topic_id, t("Cannot add section to a non-section-specific discussion")) end def course_and_topic_share_context - return true if self.deleted? || self.discussion_topic.context_id == self.course_section.course_id + return true if deleted? || discussion_topic.context_id == course_section.course_id - self.errors.add(:course_section_id, - t("Section does not belong to course for this discussion topic")) + errors.add(:course_section_id, + t("Section does not belong to course for this discussion topic")) end def new_discussion_topic? - self.discussion_topic&.new_record? + discussion_topic&.new_record? end def set_discussion_topic_id # rails 5.2.1 tries to validate the visibility after saving the topic but before setting the topic_id :/ - self.discussion_topic_id ||= self.discussion_topic&.id + self.discussion_topic_id ||= discussion_topic&.id end end diff --git a/app/models/enrollment.rb b/app/models/enrollment.rb index 8da5c26cd2ffc..529bedc7cee98 100644 --- a/app/models/enrollment.rb +++ b/app/models/enrollment.rb @@ -96,47 +96,47 @@ class Enrollment < ActiveRecord::Base scope :current_and_concluded, -> { joins(:course).where(QueryBuilder.new(:current_and_concluded).conditions).readonly(false) } def ensure_role_id - self.role_id ||= self.role.id + self.role_id ||= role.id end def cant_observe_self - self.errors.add(:associated_user_id, "Cannot observe yourself") if self.user_id == self.associated_user_id + errors.add(:associated_user_id, "Cannot observe yourself") if user_id == associated_user_id end def valid_course? if !deleted? && course.deleted? - self.errors.add(:course_id, "is not a valid course") + errors.add(:course_id, "is not a valid course") end end def not_template_course? if course.template? - self.errors.add(:course_id, "is a template course") + errors.add(:course_id, "is a template course") end end def valid_section? unless deleted? || course_section.active? - self.errors.add(:course_section_id, "is not a valid section") + errors.add(:course_section_id, "is not a valid section") end end def not_student_view if type != 'StudentViewEnrollment' && (new_record? || association(:user).loaded?) && user.fake_student? - self.errors.add(:user_id, "cannot add a student view student in a regular role") + errors.add(:user_id, "cannot add a student view student in a regular role") end end def valid_role? - return true if self.deleted? || role.built_in? + return true if deleted? || role.built_in? - unless self.role.base_role_type == self.type - self.errors.add(:role_id, "is not valid for the enrollment type") + unless role.base_role_type == type + errors.add(:role_id, "is not valid for the enrollment type") end - unless self.course.account.valid_role?(role) - self.errors.add(:role_id, "is not an available role for this course's account") + unless course.account.valid_role?(role) + errors.add(:role_id, "is not an available role for this course's account") end end @@ -147,7 +147,7 @@ def self.get_built_in_role_for_type(enrollment_type, root_account_id:) end def default_role - Enrollment.get_built_in_role_for_type(self.type, root_account_id: self.course.root_account_id) + Enrollment.get_built_in_role_for_type(type, root_account_id: course.root_account_id) end # see #active_student? @@ -196,7 +196,7 @@ def needs_grading_count_updated set_broadcast_policy do |p| p.dispatch :enrollment_invitation - p.to { self.user } + p.to { user } p.whenever { |record| !record.self_enrolled && record.course && @@ -206,7 +206,7 @@ def needs_grading_count_updated } p.dispatch :enrollment_registration - p.to { self.user.communication_channel } + p.to { user.communication_channel } p.whenever { |record| !record.self_enrolled && record.course && @@ -215,7 +215,7 @@ def needs_grading_count_updated } p.dispatch :enrollment_notification - p.to { self.user } + p.to { user } p.whenever { |record| !record.self_enrolled && record.course && @@ -225,7 +225,7 @@ def needs_grading_count_updated } p.dispatch :enrollment_accepted - p.to { self.course.participating_admins.restrict_to_sections([self.course_section_id]) - [self.user] } + p.to { course.participating_admins.restrict_to_sections([course_section_id]) - [user] } p.whenever { |record| record.course && !record.observer? && @@ -235,10 +235,10 @@ def needs_grading_count_updated def dispatch_invitations_later # if in an invited state but not frd "invited?" because of future date restrictions, send it later - if (self.just_created || self.saved_change_to_workflow_state? || @re_send_confirmation) && self.workflow_state == 'invited' && self.inactive? && self.available_at && - !self.self_enrolled && !(self.observer? && self.user.registered?) + if (just_created || saved_change_to_workflow_state? || @re_send_confirmation) && workflow_state == 'invited' && inactive? && available_at && + !self_enrolled && !(observer? && user.registered?) # this won't work if they invite them and then change the course/term/section dates _afterwards_ so hopefully people don't do that - delay(run_at: self.available_at, singleton: "send_enrollment_invitations_#{global_id}").re_send_confirmation_if_invited! + delay(run_at: available_at, singleton: "send_enrollment_invitations_#{global_id}").re_send_confirmation_if_invited! end end @@ -320,11 +320,11 @@ def self.sis_type(type) end def sis_type - Enrollment.sis_type(self.type) + Enrollment.sis_type(type) end def sis_role - (!self.role.built_in? && self.role.name) || Enrollment.sis_type(self.type) + (!role.built_in? && role.name) || Enrollment.sis_type(type) end def self.valid_types @@ -341,44 +341,44 @@ def reload(options = nil) end def should_update_user_account_association? - self.id_before_last_save.nil? || self.saved_change_to_course_id? || self.saved_change_to_course_section_id? || - self.saved_change_to_root_account_id? || being_restored? + id_before_last_save.nil? || saved_change_to_course_id? || saved_change_to_course_section_id? || + saved_change_to_root_account_id? || being_restored? end def update_user_account_associations_if_necessary - return if self.fake_student? + return if fake_student? if id_before_last_save.nil? || being_restored? - return if %w[creation_pending deleted].include?(self.user.workflow_state) + return if %w[creation_pending deleted].include?(user.workflow_state) - associations = User.calculate_account_associations_from_accounts([self.course.account_id, self.course_section.course.account_id, self.course_section.nonxlist_course.try(:account_id)].compact.uniq) - self.user.update_account_associations(:incremental => true, :precalculated_associations => associations) + associations = User.calculate_account_associations_from_accounts([course.account_id, course_section.course.account_id, course_section.nonxlist_course.try(:account_id)].compact.uniq) + user.update_account_associations(:incremental => true, :precalculated_associations => associations) elsif should_update_user_account_association? - self.user.update_account_associations_later + user.update_account_associations_later end end protected :update_user_account_associations_if_necessary def other_section_enrollment_exists? # If other active sessions that the user is enrolled in exist. - self.course.student_enrollments.where.not(:workflow_state => ['deleted', 'rejected']).for_user(self.user).where.not(id: self.id).exists? + course.student_enrollments.where.not(:workflow_state => ['deleted', 'rejected']).for_user(user).where.not(id: id).exists? end def audit_groups_for_deleted_enrollments # did the student cease to be enrolled in a non-deleted state in a section? - had_section = self.course_section_id_was.present? + had_section = course_section_id_was.present? deleted_states = ['deleted', 'rejected'] - was_active = !deleted_states.include?(self.workflow_state_was) - is_deleted = deleted_states.include?(self.workflow_state) + was_active = !deleted_states.include?(workflow_state_was) + is_deleted = deleted_states.include?(workflow_state) return unless had_section && was_active && - (self.course_section_id_changed? || is_deleted) + (course_section_id_changed? || is_deleted) # what section the user is abandoning, and the section they're moving to # (if it's in the same course and the enrollment's not deleted) - section = CourseSection.find(self.course_section_id_was) + section = CourseSection.find(course_section_id_was) # ok, consider groups the user is in from the abandoned section's course - self.user.groups.preload(:group_category).where( + user.groups.preload(:group_category).where( :context_type => 'Course', :context_id => section.course_id ).each do |group| # check group deletion criteria if either enrollment is not a deletion @@ -389,7 +389,7 @@ def audit_groups_for_deleted_enrollments # skip if the user is the only user in the group. there's no one to have # a conflicting section. - next unless group.users.where.not(id: self.user_id).exists? + next unless group.users.where.not(id: user_id).exists? # check if the group has the section the user is abandoning as a common # section (from CourseSection#common_to_users? view, the enrollment is @@ -403,14 +403,14 @@ def audit_groups_for_deleted_enrollments # remove the user from the group. Or the student was only enrolled in one section and # by leaving the section he/she is completely leaving the course so remove the # user from any group related to the course. - membership = group.group_memberships.where(user_id: self.user_id).first + membership = group.group_memberships.where(user_id: user_id).first membership&.destroy end end protected :audit_groups_for_deleted_enrollments def observers - student? ? user.linked_observers.active.linked_through_root_account(self.root_account) : [] + student? ? user.linked_observers.active.linked_through_root_account(root_account) : [] end def create_linked_enrollments @@ -424,7 +424,7 @@ def update_linked_enrollments(restore: false) enrollment = restore ? linked_enrollment_for(observer) : active_linked_enrollment_for(observer) if enrollment enrollment.update_from(self) - elsif restore || (self.saved_change_to_workflow_state? && ['inactive', 'deleted'].include?(self.workflow_state_before_last_save)) + elsif restore || (saved_change_to_workflow_state? && ['inactive', 'deleted'].include?(workflow_state_before_last_save)) create_linked_enrollment_for(observer) end end @@ -480,7 +480,7 @@ def update_cached_due_dates def update_from(other, skip_broadcasts = false) self.course_id = other.course_id - self.workflow_state = if self.type == 'ObserverEnrollment' && other.workflow_state == 'invited' + self.workflow_state = if type == 'ObserverEnrollment' && other.workflow_state == 'invited' 'active' else other.workflow_state @@ -498,20 +498,20 @@ def update_from(other, skip_broadcasts = false) end def clear_email_caches - if self.saved_change_to_workflow_state? && (self.workflow_state_before_last_save == 'invited' || self.workflow_state == 'invited') + if saved_change_to_workflow_state? && (workflow_state_before_last_save == 'invited' || workflow_state == 'invited') if Enrollment.cross_shard_invitations? Shard.birth.activate do - self.user.communication_channels.email.unretired.each { |cc| Rails.cache.delete([cc.path, 'all_invited_enrollments2'].cache_key) } + user.communication_channels.email.unretired.each { |cc| Rails.cache.delete([cc.path, 'all_invited_enrollments2'].cache_key) } end else - self.user.communication_channels.email.unretired.each { |cc| Rails.cache.delete([cc.path, 'invited_enrollments2'].cache_key) } + user.communication_channels.email.unretired.each { |cc| Rails.cache.delete([cc.path, 'invited_enrollments2'].cache_key) } end end end def cancel_future_appointments if saved_change_to_workflow_state? && %w[completed deleted].include?(workflow_state) - unless self.course.current_enrollments.where(:user_id => self.user_id).exists? # ignore if they have another still valid enrollment + unless course.current_enrollments.where(:user_id => user_id).exists? # ignore if they have another still valid enrollment course.appointment_participants.active.current.for_context_codes(user.asset_string).update_all(:workflow_state => 'deleted') end end @@ -520,87 +520,87 @@ def cancel_future_appointments def conclude self.workflow_state = "completed" self.completed_at = Time.now - self.save + save end def unconclude self.workflow_state = 'active' self.completed_at = nil - self.save + save end def deactivate self.workflow_state = "inactive" - self.save + save end def reactivate self.workflow_state = "active" - self.save + save end def defined_by_sis? - !!self.sis_batch_id + !!sis_batch_id end def assigned_observer? - self.observer? && self.associated_user_id + observer? && associated_user_id end def participating? - self.state_based_on_date == :active + state_based_on_date == :active end def participating_student? - self.student? && self.participating? + student? && participating? end def participating_observer? - self.observer? && self.participating? + observer? && participating? end def participating_teacher? - self.teacher? && self.participating? + teacher? && participating? end def participating_ta? - self.ta? && self.participating? + ta? && participating? end def participating_instructor? - self.instructor? && self.participating? + instructor? && participating? end def participating_designer? - self.designer? && self.participating? + designer? && participating? end def participating_admin? - self.admin? && self.participating? + admin? && participating? end def participating_content_admin? - self.content_admin? && self.participating? + content_admin? && participating? end def associated_user_name - self.associated_user&.short_name + associated_user&.short_name end def assert_section - self.course_section = self.course.default_section if !self.course_section_id && self.course - self.root_account_id ||= self.course.root_account_id rescue nil + self.course_section = course.default_section if !course_section_id && course + self.root_account_id ||= course.root_account_id rescue nil end def course_name(display_user = nil) - self.course.nickname_for(display_user) || t('#enrollment.default_course_name', "Course") + course.nickname_for(display_user) || t('#enrollment.default_course_name', "Course") end def short_name(length = nil, display_user = nil) return @short_name if @short_name - @short_name = self.course_section.display_name if self.course_section && self.root_account && self.root_account.show_section_name_as_course_name - @short_name ||= self.course_name(display_user) + @short_name = course_section.display_name if course_section && root_account && root_account.show_section_name_as_course_name + @short_name ||= course_name(display_user) @short_name = @short_name[0..length] if length @short_name end @@ -608,8 +608,8 @@ def short_name(length = nil, display_user = nil) def long_name(display_user = nil) return @long_name if @long_name - @long_name = self.course_name(display_user) - @long_name = t('#enrollment.with_section', "%{course_name}, %{section_name}", :course_name => @long_name, :section_name => self.course_section.display_name) if self.course_section&.display_name && self.course_section.display_name != self.course_name(display_user) + @long_name = course_name(display_user) + @long_name = t('#enrollment.with_section', "%{course_name}, %{section_name}", :course_name => @long_name, :section_name => course_section.display_name) if course_section&.display_name && course_section.display_name != course_name(display_user) @long_name end @@ -661,8 +661,8 @@ def accept(force = false) return false unless force || invited? if update_attribute(:workflow_state, 'active') - if self.type == 'StudentEnrollment' - Enrollment.recompute_final_score_in_singleton(self.user_id, self.course_id) + if type == 'StudentEnrollment' + Enrollment.recompute_final_score_in_singleton(user_id, course_id) end true end @@ -670,13 +670,13 @@ def accept(force = false) end def reset_notifications_cache - if self.saved_change_to_workflow_state? - StreamItemCache.invalidate_recent_stream_items(self.user_id, "Course", self.course_id) + if saved_change_to_workflow_state? + StreamItemCache.invalidate_recent_stream_items(user_id, "Course", course_id) end end def add_to_favorites_later - if self.saved_change_to_workflow_state? && self.workflow_state == 'active' + if saved_change_to_workflow_state? && workflow_state == 'active' self.class.connection.after_transaction_commit do delay_if_production(priority: Delayed::LOW_PRIORITY).add_to_favorites end @@ -689,7 +689,7 @@ def self.batch_add_to_favorites(enrollment_ids) def add_to_favorites # this method was written by Alan Smithee - self.user.shard.activate do + user.shard.activate do if user.favorites.where(:context_type => 'Course').exists? # only add a favorite if they've ever favorited anything even if it's no longer in effect Favorite.unique_constraint_retry do user.favorites.where(:context_type => 'Course', :context_id => course).first_or_create! @@ -742,7 +742,7 @@ def enrollment_state def create_enrollment_state self.enrollment_state = - self.shard.activate do + shard.activate do GuardRail.activate(:primary) do EnrollmentState.unique_constraint_retry do EnrollmentState.where(:enrollment_id => self).first_or_create @@ -752,21 +752,21 @@ def create_enrollment_state end def recalculate_enrollment_state - if (self.saved_changes.keys & %w[workflow_state start_at end_at]).any? + if (saved_changes.keys & %w[workflow_state start_at end_at]).any? @enrollment_dates = nil - self.enrollment_state.state_is_current = false - self.enrollment_state.is_direct_recalculation = true + enrollment_state.state_is_current = false + enrollment_state.is_direct_recalculation = true end - self.enrollment_state.skip_touch_user ||= self.skip_touch_user - self.enrollment_state.ensure_current_state + enrollment_state.skip_touch_user ||= skip_touch_user + enrollment_state.ensure_current_state end def state_based_on_date - RequestCache.cache('enrollment_state_based_on_date', self, self.workflow_state, self.saved_changes?) do - if %w[invited active completed].include?(self.workflow_state) - self.enrollment_state.get_effective_state + RequestCache.cache('enrollment_state_based_on_date', self, workflow_state, saved_changes?) do + if %w[invited active completed].include?(workflow_state) + enrollment_state.get_effective_state else - self.workflow_state.to_sym + workflow_state.to_sym end end end @@ -774,35 +774,35 @@ def state_based_on_date def readable_state_based_on_date # when view restrictions are in place, the effective state_based_on_date is :inactive, but # to admins we should show that they are :completed or :pending - self.enrollment_state.get_display_state + enrollment_state.get_display_state end def available_at - if self.enrollment_state.pending? - self.enrollment_state.state_valid_until + if enrollment_state.pending? + enrollment_state.state_valid_until end end def view_restrictable? - (self.student? && !self.fake_student?) || self.observer? + (student? && !fake_student?) || observer? end def restrict_past_view? - self.view_restrictable? && RequestCache.cache('restrict_student_past_view', self.global_course_id) do - self.course.restrict_student_past_view? + view_restrictable? && RequestCache.cache('restrict_student_past_view', global_course_id) do + course.restrict_student_past_view? end end def restrict_future_view? - self.view_restrictable? && RequestCache.cache('restrict_student_future_view', self.global_course_id) do - self.course.restrict_student_future_view? + view_restrictable? && RequestCache.cache('restrict_student_future_view', global_course_id) do + course.restrict_student_future_view? end end def restrict_future_listing? - self.enrollment_state.pending? && - (self.enrollment_state.restricted_access? || (!self.admin? && self.course.unpublished?)) && - self.course.account.restrict_student_future_listing[:value] + enrollment_state.pending? && + (enrollment_state.restricted_access? || (!admin? && course.unpublished?)) && + course.account.restrict_student_future_listing[:value] end def active? @@ -826,7 +826,7 @@ def accepted? end def completed? - self.enrollment_state.get_display_state == :completed + enrollment_state.get_display_state == :completed end def explicitly_completed? @@ -834,19 +834,19 @@ def explicitly_completed? end def completed_at - if (date = self.read_attribute(:completed_at)) + if (date = read_attribute(:completed_at)) date elsif !new_record? && completed? - self.enrollment_state.state_started_at + enrollment_state.state_started_at end end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - result = self.save + result = save if result - self.user.try(:update_account_associations) + user.try(:update_account_associations) scores.update_all(updated_at: Time.zone.now, workflow_state: :deleted) Assignment.remove_user_as_final_grader(user_id, course_id) if remove_user_as_final_grader? @@ -857,19 +857,19 @@ def destroy def restore self.workflow_state = 'active' self.completed_at = nil - self.save + save true end def re_send_confirmation! @re_send_confirmation = true - self.save + save @re_send_confirmation = false true end def re_send_confirmation_if_invited! - self.re_send_confirmation! if self.invited? + re_send_confirmation! if invited? end def has_permission_to?(action) @@ -894,7 +894,7 @@ def base_role_name def can_be_concluded_by(user, context, session) can_remove = [StudentEnrollment].include?(self.class) && context.grants_right?(user, session, :manage_students) && - context.id == ((context.is_a? Course) ? self.course_id : self.course_section_id) + context.id == ((context.is_a? Course) ? course_id : course_section_id) can_remove || context.grants_right?(user, session, manage_admin_users_perm) end @@ -908,27 +908,27 @@ def can_be_concluded_by(user, context, session) def can_be_deleted_by(user, context, session) return context.grants_right?(user, session, :use_student_view) if fake_student? - if self.root_account.feature_enabled? :granular_permissions_manage_users + if root_account.feature_enabled? :granular_permissions_manage_users can_remove = can_delete_via_granular(user, session, context) - can_remove &&= self.user_id != user.id || context.account.grants_right?(user, session, :allow_course_admin_actions) + can_remove &&= user_id != user.id || context.account.grants_right?(user, session, :allow_course_admin_actions) else can_remove = context.grants_right?(user, session, :manage_admin_users) && !student? can_remove ||= [StudentEnrollment, ObserverEnrollment].include?(self.class) && context.grants_right?(user, session, :manage_students) - can_remove &&= self.user_id != user.id || context.account.grants_right?(user, session, :manage_admin_users) + can_remove &&= user_id != user.id || context.account.grants_right?(user, session, :manage_admin_users) end - can_remove && context.id == (context.is_a?(Course) ? self.course_id : self.course_section_id) + can_remove && context.id == (context.is_a?(Course) ? course_id : course_section_id) end def pending? - self.invited? || self.creation_pending? + invited? || creation_pending? end def email - self.user.email rescue t('#enrollment.default_email', "No Email") + user.email rescue t('#enrollment.default_email', "No Email") end def user_name - read_attribute(:user_name) || self.user.name rescue t('#enrollment.default_user_name', "Unknown User") + read_attribute(:user_name) || user.name rescue t('#enrollment.default_user_name', "Unknown User") end def context @@ -971,7 +971,7 @@ def self.workflow_readable_type(state) end def readable_role_name - self.role.built_in? ? self.readable_type : self.role.name + role.built_in? ? readable_type : role.name end def readable_type @@ -1233,35 +1233,35 @@ def content_admin? def to_atom Atom::Entry.new do |entry| - entry.title = t('#enrollment.title', "%{user_name} in %{course_name}", :user_name => self.user_name, :course_name => self.course_name) - entry.updated = self.updated_at - entry.published = self.created_at + entry.title = t('#enrollment.title', "%{user_name} in %{course_name}", :user_name => user_name, :course_name => course_name) + entry.updated = updated_at + entry.published = created_at entry.links << Atom::Link.new(:rel => 'alternate', - :href => "/courses/#{self.course.id}/enrollments/#{self.id}") + :href => "/courses/#{course.id}/enrollments/#{id}") end end set_policy do - given { |user, session| self.course.grants_any_right?(user, session, :manage_students, manage_admin_users_perm, :read_roster) } + given { |user, session| course.grants_any_right?(user, session, :manage_students, manage_admin_users_perm, :read_roster) } can :read given { |user| self.user == user } can :read and can :read_grades given { |user, session| - self.course.students_visible_to(user, include: :priors).where(:id => self.user_id).exists? && - self.course.grants_any_right?(user, session, :manage_grades, :view_all_grades) + course.students_visible_to(user, include: :priors).where(:id => user_id).exists? && + course.grants_any_right?(user, session, :manage_grades, :view_all_grades) } can :read and can :read_grades - given { |user| course.observer_enrollments.where(user_id: user, associated_user_id: self.user_id).exists? } + given { |user| course.observer_enrollments.where(user_id: user, associated_user_id: user_id).exists? } can :read and can :read_grades - given { |user, session| self.course.grants_right?(user, session, :participate_as_student) && self.user.show_user_services } + given { |user, session| course.grants_right?(user, session, :participate_as_student) && self.user.show_user_services } can :read_services # read_services says this person has permission to see what web services this enrollment has linked to their account - given { |user, session| self.grants_right?(user, session, :read) && self.user.show_user_services } + given { |user, session| grants_right?(user, session, :read) && self.user.show_user_services } can :read_services end @@ -1340,11 +1340,11 @@ def self.cached_temporary_invitations(email) def self.order_by_sortable_name clause = User.sortable_name_order_by_clause('users') - scope = self.order(clause) + scope = order(clause) if scope.select_values.present? scope.select(clause) else - scope.select(self.arel_table[Arel.star]) + scope.select(arel_table[Arel.star]) end end @@ -1364,7 +1364,7 @@ def assign_uuid def uuid unless read_attribute(:uuid) - self.update_attribute(:uuid, CanvasSlug.generate_securish_uuid) + update_attribute(:uuid, CanvasSlug.generate_securish_uuid) end read_attribute(:uuid) end @@ -1400,9 +1400,7 @@ def self.serialization_excludes # enrollment term per-section is deprecated; a section's term is inherited from the # course it is currently tied to - def enrollment_term - self.course.enrollment_term - end + delegate :enrollment_term, to: :course def effective_start_at # try and use the enrollment dates logic first, since it knows about @@ -1434,20 +1432,20 @@ def self.cross_shard_invitations? end def total_activity_time - self.read_attribute(:total_activity_time).to_i + read_attribute(:total_activity_time).to_i end def touch_graders_if_needed - if !active_student? && active_student?(:was) && self.course.submissions.where(:user_id => self.user_id).exists? + if !active_student? && active_student?(:was) && course.submissions.where(:user_id => user_id).exists? self.class.connection.after_transaction_commit do - self.course.admins.clear_cache_keys(:todo_list) + course.admins.clear_cache_keys(:todo_list) end end end def update_assignment_overrides_if_needed - assignment_scope = Assignment.where(context_id: self.course_id, context_type: 'Course') - override_scope = AssignmentOverrideStudent.where(user_id: self.user_id) + assignment_scope = Assignment.where(context_id: course_id, context_type: 'Course') + override_scope = AssignmentOverrideStudent.where(user_id: user_id) if being_deleted? && !enrollments_exist_for_user_in_course? return unless (assignment_ids = assignment_scope.pluck(:id)).any? @@ -1459,7 +1457,7 @@ def update_assignment_overrides_if_needed end if being_accepted? - return unless ConditionalRelease::Service.enabled_in_context?(self.course) + return unless ConditionalRelease::Service.enabled_in_context?(course) # Deleted student overrides associated with assignments with a Mastery Path override releases = override_scope.where(workflow_state: 'deleted') @@ -1486,10 +1484,10 @@ def update_assignment_overrides_if_needed end def section_or_course_date_in_past? - if self.course_section&.end_at - self.course_section.end_at < Time.zone.now - elsif self.course.conclude_at - self.course.conclude_at < Time.zone.now + if course_section&.end_at + course_section.end_at < Time.zone.now + elsif course.conclude_at + course.conclude_at < Time.zone.now end end @@ -1498,13 +1496,13 @@ def student_or_fake_student? end def allows_favoriting? - !(self.course.elementary_subject_course? || self.course.elementary_homeroom_course?) || teacher? || ta? || designer? || self.user.roles(self.root_account).include?('teacher') + !(course.elementary_subject_course? || course.elementary_homeroom_course?) || teacher? || ta? || designer? || user.roles(root_account).include?('teacher') end private def enrollments_exist_for_user_in_course? - Enrollment.active.where(user_id: self.user_id, course_id: self.course_id).exists? + Enrollment.active.where(user_id: user_id, course_id: course_id).exists? end def copy_scores_from_existing_enrollment @@ -1533,15 +1531,15 @@ def other_enrollments_of_type(types) end def manage_admin_users_perm - self.root_account.feature_enabled?(:granular_permissions_manage_users) ? :allow_course_admin_actions : :manage_admin_users + root_account.feature_enabled?(:granular_permissions_manage_users) ? :allow_course_admin_actions : :manage_admin_users end def can_delete_via_granular(user, session, context) - (self.teacher? && context.grants_right?(user, session, :remove_teacher_from_course)) || - (self.ta? && context.grants_right?(user, session, :remove_ta_from_course)) || - (self.designer? && context.grants_right?(user, session, :remove_designer_from_course)) || - (self.observer? && context.grants_right?(user, session, :remove_observer_from_course)) || - (self.student? && context.grants_right?(user, session, :remove_student_from_course)) + (teacher? && context.grants_right?(user, session, :remove_teacher_from_course)) || + (ta? && context.grants_right?(user, session, :remove_ta_from_course)) || + (designer? && context.grants_right?(user, session, :remove_designer_from_course)) || + (observer? && context.grants_right?(user, session, :remove_observer_from_course)) || + (student? && context.grants_right?(user, session, :remove_student_from_course)) end def remove_user_as_final_grader? @@ -1570,9 +1568,9 @@ def being_deleted? end def sync_microsoft_group - return if self.type == 'StudentViewEnrollment' - return unless self.root_account.feature_enabled?(:microsoft_group_enrollments_syncing) - return unless self.root_account.settings[:microsoft_sync_enabled] + return if type == 'StudentViewEnrollment' + return unless root_account.feature_enabled?(:microsoft_group_enrollments_syncing) + return unless root_account.settings[:microsoft_sync_enabled] MicrosoftSync::Group.not_deleted.find_by(course_id: course_id)&.enqueue_future_partial_sync self end diff --git a/app/models/enrollment_dates_override.rb b/app/models/enrollment_dates_override.rb index 09c2b1fa948fe..9fd082466647c 100644 --- a/app/models/enrollment_dates_override.rb +++ b/app/models/enrollment_dates_override.rb @@ -25,8 +25,8 @@ class EnrollmentDatesOverride < ActiveRecord::Base after_save :update_courses_and_states_if_necessary def update_courses_and_states_if_necessary - if self.saved_changes? - self.enrollment_term.update_courses_and_states_later(self.enrollment_type) + if saved_changes? + enrollment_term.update_courses_and_states_later(enrollment_type) end end end diff --git a/app/models/enrollment_state.rb b/app/models/enrollment_state.rb index bb91b008ed560..acad1aa5eb9db 100644 --- a/app/models/enrollment_state.rb +++ b/app/models/enrollment_state.rb @@ -50,26 +50,26 @@ class EnrollmentState < ActiveRecord::Base # check if we've manually marked the enrollment state as potentially out of date (or if the stored date trigger has past) def state_needs_recalculation? - !self.state_is_current? || (self.state_valid_until && self.state_valid_until < Time.now) + !state_is_current? || (state_valid_until && state_valid_until < Time.now) end def ensure_current_state GuardRail.activate(:primary) do retry_count = 0 begin - self.recalculate_state if self.state_needs_recalculation? || retry_count > 0 # force double-checking on lock conflict - self.recalculate_access if !self.access_is_current? || retry_count > 0 - self.save! if self.changed? + recalculate_state if state_needs_recalculation? || retry_count > 0 # force double-checking on lock conflict + recalculate_access if !access_is_current? || retry_count > 0 + save! if changed? rescue ActiveRecord::StaleObjectError # retry up to five times, otherwise return current (stale) data - self.enrollment.association(:enrollment_state).target = nil # don't cache an old enrollment state, just in case - self.reload + enrollment.association(:enrollment_state).target = nil # don't cache an old enrollment state, just in case + reload retry_count += 1 retry if retry_count < 5 - logger.error { "Failed to evaluate stale enrollment state: #{self.inspect}" } + logger.error { "Failed to evaluate stale enrollment state: #{inspect}" } end end end @@ -79,61 +79,61 @@ def ensure_current_state # - an invitation in a course yet to start is functionally identical to an invitation in a started course # - :accepted is kind of silly, but it's how the old code signified an active enrollment in a course that hadn't started def get_effective_state - self.ensure_current_state + ensure_current_state if restricted_access? :inactive - elsif self.state == 'pending_invited' + elsif state == 'pending_invited' :invited - elsif self.state == 'pending_active' + elsif state == 'pending_active' :accepted else - self.state.to_sym + state.to_sym end end def get_display_state - self.ensure_current_state + ensure_current_state if pending? :pending else - self.state.to_sym + state.to_sym end end def pending? - %w[pending_active pending_invited creation_pending].include?(self.state) + %w[pending_active pending_invited creation_pending].include?(state) end def recalculate_state self.state_valid_until = nil self.state_started_at = nil - wf_state = self.enrollment.workflow_state + wf_state = enrollment.workflow_state invited_or_active = %w[invited active].include?(wf_state) if invited_or_active - if self.enrollment.course.completed? + if enrollment.course.completed? self.state = 'completed' else - self.calculate_state_based_on_dates + calculate_state_based_on_dates end else self.state = wf_state end self.state_is_current = true - if self.state_changed? && self.enrollment.view_restrictable? + if state_changed? && enrollment.view_restrictable? self.access_is_current = false end - if self.state_changed? + if state_changed? self.user_needs_touch = true - unless self.skip_touch_user + unless skip_touch_user self.class.connection.after_transaction_commit do - self.enrollment.user.touch unless User.skip_touch_for_type?(:enrollments) - self.enrollment.user.clear_cache_key(:enrollments) + enrollment.user.touch unless User.skip_touch_for_type?(:enrollments) + enrollment.user.clear_cache_key(:enrollments) end end end @@ -144,8 +144,8 @@ def recalculate_state # so this translates the current enrollment's workflow_state depending # whether we're currently before the start, after the end, or between the two def calculate_state_based_on_dates - wf_state = self.enrollment.workflow_state - ranges = self.enrollment.enrollment_dates + wf_state = enrollment.workflow_state + ranges = enrollment.enrollment_dates now = Time.now # start_at <= now <= end_at, allowing for open ranges on either end @@ -165,13 +165,13 @@ def calculate_state_based_on_dates # we've past the end date so no matter what the state was, we're "completed" now self.state_started_at = ranges.filter_map(&:last).min self.state = 'completed' - elsif self.enrollment.fake_student? # rubocop:disable Lint/DuplicateBranch + elsif enrollment.fake_student? # rubocop:disable Lint/DuplicateBranch # Allow student view students to use the course before the term starts self.state = wf_state else # the course has yet to begin for the enrollment self.state_valid_until = global_start_at # store the date when that will change - self.state = if self.enrollment.view_restrictable? + self.state = if enrollment.view_restrictable? # these enrollment states mean they still can't participate yet even if they've accepted it, # but should be able to view just like an invited enrollment if wf_state == 'active' @@ -191,11 +191,11 @@ def calculate_state_based_on_dates # you can still access the course in a "view-only" mode # but courses/accounts can disable this def recalculate_access - self.restricted_access = if self.enrollment.view_restrictable? - if self.pending? - self.enrollment.restrict_future_view? - elsif self.state == 'completed' - self.enrollment.restrict_past_view? + self.restricted_access = if enrollment.view_restrictable? + if pending? + enrollment.restrict_future_view? + elsif state == 'completed' + enrollment.restrict_past_view? else false end diff --git a/app/models/enrollment_term.rb b/app/models/enrollment_term.rb index 3d2b4824b7c78..b7d338410c20d 100644 --- a/app/models/enrollment_term.rb +++ b/app/models/enrollment_term.rb @@ -49,24 +49,24 @@ def self.ensure_dummy_enrollment_term end def prevent_default_term_name_change - if self.name_changed? && self.name_was == DEFAULT_TERM_NAME && self == self.root_account.default_enrollment_term - self.errors.add(:name, t("Cannot change the default term name")) + if name_changed? && name_was == DEFAULT_TERM_NAME && self == root_account.default_enrollment_term + errors.add(:name, t("Cannot change the default term name")) end end def check_if_deletable - if self.workflow_state_changed? && self.workflow_state == "deleted" - if self.default_term? - self.errors.add(:workflow_state, t('errors.delete_default_term', "Cannot delete the default term")) - elsif self.courses.active.exists? - self.errors.add(:workflow_state, t('errors.delete_term_with_courses', "Cannot delete a term with active courses")) + if workflow_state_changed? && workflow_state == "deleted" + if default_term? + errors.add(:workflow_state, t('errors.delete_default_term', "Cannot delete the default term")) + elsif courses.active.exists? + errors.add(:workflow_state, t('errors.delete_term_with_courses', "Cannot delete a term with active courses")) end end end def update_courses_later_if_necessary - if !self.new_record? && (self.saved_change_to_start_at? || self.saved_change_to_end_at?) - self.update_courses_and_states_later + if !new_record? && (saved_change_to_start_at? || saved_change_to_end_at?) + update_courses_and_states_later end end @@ -76,16 +76,16 @@ def reset_touched_courses_flag end def touch_all_courses - self.courses.touch_all + courses.touch_all end def update_courses_and_states_later(enrollment_type = nil) return if new_record? - delay_if_production(singleton: "EnrollmentTerm#touch_all_courses_#{self.global_id}").touch_all_courses unless @touched_courses + delay_if_production(singleton: "EnrollmentTerm#touch_all_courses_#{global_id}").touch_all_courses unless @touched_courses @touched_courses = true - EnrollmentState.delay_if_production(singleton: "EnrollmentState.invalidate_states_for_term_#{self.global_id}_#{enrollment_type}") + EnrollmentState.delay_if_production(singleton: "EnrollmentState.invalidate_states_for_term_#{global_id}_#{enrollment_type}") .invalidate_states_for_term(self, enrollment_type) end @@ -127,7 +127,7 @@ def set_overrides(context, params) params.map do |type, values| type = type.classify enrollment_type = Enrollment.typed_enrollment(type).to_s - override = self.enrollment_dates_overrides.where(enrollment_type: enrollment_type).first_or_initialize + override = enrollment_dates_overrides.where(enrollment_type: enrollment_type).first_or_initialize # preload the reverse association - VERY IMPORTANT so that @touched_enrollments is shared override.enrollment_term = self override.start_at = values[:start_at] @@ -139,15 +139,15 @@ def set_overrides(context, params) end def verify_unique_sis_source_id - return true unless self.sis_source_id + return true unless sis_source_id return true if !root_account_id_changed? && !sis_source_id_changed? - scope = root_account.enrollment_terms.where(sis_source_id: self.sis_source_id) - scope = scope.where("id<>?", self) unless self.new_record? + scope = root_account.enrollment_terms.where(sis_source_id: sis_source_id) + scope = scope.where("id<>?", self) unless new_record? return true unless scope.exists? - self.errors.add(:sis_source_id, t('errors.not_unique', "SIS ID \"%{sis_source_id}\" is already in use", :sis_source_id => self.sis_source_id)) + errors.add(:sis_source_id, t('errors.not_unique', "SIS ID \"%{sis_source_id}\" is already in use", :sis_source_id => sis_source_id)) throw :abort end diff --git a/app/models/eportfolio.rb b/app/models/eportfolio.rb index 4c17598dbb390..4cd088766b99b 100644 --- a/app/models/eportfolio.rb +++ b/app/models/eportfolio.rb @@ -49,13 +49,13 @@ class Eportfolio < ActiveRecord::Base def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - self.save + save end def restore self.workflow_state = 'active' self.deleted_at = nil - self.save + save end def flagged_as_possible_spam? @@ -88,43 +88,43 @@ def assign_uuid # User is the author and eportfolios are enabled (whether this eportfolio # is spam or not, the author can see it and delete it). - given { |user| self.active? && self.user == user && user.eportfolios_enabled? } + given { |user| active? && self.user == user && user.eportfolios_enabled? } can :read and can :delete # If an eportfolio has been flagged as possible spam or marked as spam, don't let the author # update it. If an admin marks the content as safe, the user will be able to make updates again, # but we don't want to let the user make changes before an admin can review the content. - given { |user| self.active? && self.user == user && user.eportfolios_enabled? && !self.spam? } + given { |user| active? && self.user == user && user.eportfolios_enabled? && !spam? } can :update and can :manage # The eportfolio is public, eportfolios are enabled, and it hasn't been flagged or marked as spam. - given { |_| self.active? && self.public && !self.spam? && self.user.eportfolios_enabled? } + given { |_| active? && public && !spam? && self.user.eportfolios_enabled? } can :read # The eportfolio is private and the user has access to the private link # (we know this by way of the session having the eportfolio id) and the # eportfolio hasn't been flagged or marked as spam. given do |_, session| - self.active? && session && session[:eportfolio_ids] && - session[:eportfolio_ids].include?(self.id) && - !self.spam? + active? && session && session[:eportfolio_ids] && + session[:eportfolio_ids].include?(id) && + !spam? end can :read given do |user| - self.user != user && self.active? && self.user&.grants_right?(user, :moderate_user_content) + self.user != user && active? && self.user&.grants_right?(user, :moderate_user_content) end can :read and can :moderate and can :delete and can :restore given do |user| - self.user != user && self.deleted? && self.user&.grants_right?(user, :moderate_user_content) + self.user != user && deleted? && self.user&.grants_right?(user, :moderate_user_content) end can :restore end def ensure_defaults - cat = self.eportfolio_categories.first - cat ||= self.eportfolio_categories.create!(name: t(:first_category, 'Home')) + cat = eportfolio_categories.first + cat ||= eportfolio_categories.create!(name: t(:first_category, 'Home')) if cat && cat.eportfolio_entries.empty? entry = cat.eportfolio_entries.build(eportfolio: self, name: t('first_entry.title', 'Welcome')) diff --git a/app/models/eportfolio_category.rb b/app/models/eportfolio_category.rb index b975629d7d72f..2e03f901c0b61 100644 --- a/app/models/eportfolio_category.rb +++ b/app/models/eportfolio_category.rb @@ -33,13 +33,13 @@ class EportfolioCategory < ActiveRecord::Base acts_as_list :scope => :eportfolio def infer_unique_slug - categories = self.eportfolio.eportfolio_categories + categories = eportfolio.eportfolio_categories self.name ||= t(:default_section, "Section Name") self.slug = self.name.gsub(/\s+/, "_").gsub(/[^\w\d]/, "") - categories = categories.where("id<>?", self) unless self.new_record? - match_cnt = categories.where(:slug => self.slug).count + categories = categories.where("id<>?", self) unless new_record? + match_cnt = categories.where(:slug => slug).count if match_cnt > 0 - self.slug = self.slug + "_" + (match_cnt + 1).to_s + self.slug = slug + "_" + (match_cnt + 1).to_s end end protected :infer_unique_slug diff --git a/app/models/eportfolio_entry.rb b/app/models/eportfolio_entry.rb index 58e366dff9cfe..868451b6ab9dc 100644 --- a/app/models/eportfolio_entry.rb +++ b/app/models/eportfolio_entry.rb @@ -41,23 +41,23 @@ class EportfolioEntry < ActiveRecord::Base serialize :content set_policy do - given { |user| user && self.allow_comments } + given { |user| user && allow_comments } can :comment end def infer_comment_visibility - self.show_comments = false unless self.allow_comments + self.show_comments = false unless allow_comments true end protected :infer_comment_visibility def update_portfolio - self.eportfolio.save! + eportfolio.save! end protected :update_portfolio def content_sections - ((self.content.is_a?(String) && Array(self.content)) || self.content || []).map do |section| + ((content.is_a?(String) && Array(content)) || content || []).map do |section| if section.is_a?(Hash) section.with_indifferent_access else @@ -75,14 +75,14 @@ def submission_ids end def full_slug - (self.eportfolio_category.slug rescue "") + "_" + self.slug + (eportfolio_category.slug rescue "") + "_" + slug end def attachments res = [] content_sections.each do |section| if section["attachment_id"].present? && section["section_type"] == "attachment" - res << (self.eportfolio.user.all_attachments.where(id: section["attachment_id"]).first rescue nil) + res << (eportfolio.user.all_attachments.where(id: section["attachment_id"]).first rescue nil) end end res.compact @@ -92,7 +92,7 @@ def submissions res = [] content_sections.each do |section| if section["submission_id"].present? && section["section_type"] == "submission" - res << (self.eportfolio.user.submissions.where(id: section["submission_id"]).first rescue nil) + res << (eportfolio.user.submissions.where(id: section["submission_id"]).first rescue nil) end end res.compact @@ -128,24 +128,24 @@ def parse_content(params) end if new_obj - self.content << new_obj + content << new_obj end end - self.content << t(:default_content, "No Content Added Yet") if self.content.empty? + content << t(:default_content, "No Content Added Yet") if content.empty? end def category_slug - self.eportfolio_category.slug rescue self.eportfolio_category_id + eportfolio_category.slug rescue eportfolio_category_id end def infer_unique_slug - pages = self.eportfolio_category.eportfolio_entries rescue [] + pages = eportfolio_category.eportfolio_entries rescue [] self.name ||= t(:default_name, "Page Name") self.slug = self.name.gsub(/\s+/, "_").gsub(/[^\w\d]/, "") - pages = pages.where("id<>?", self) unless self.new_record? - match_cnt = pages.where(:slug => self.slug).count + pages = pages.where("id<>?", self) unless new_record? + match_cnt = pages.where(:slug => slug).count if match_cnt > 0 - self.slug = self.slug + "_" + (match_cnt + 1).to_s + self.slug = slug + "_" + (match_cnt + 1).to_s end end protected :infer_unique_slug @@ -154,12 +154,12 @@ def to_atom(opts = {}) Atom::Entry.new do |entry| entry.title = self.name.to_s entry.authors << Atom::Person.new(:name => t(:atom_author, "ePortfolio Entry")) - entry.updated = self.updated_at - entry.published = self.created_at - url = "http://#{HostUrl.default_host}/eportfolios/#{self.eportfolio_id}/#{self.eportfolio_category.slug}/#{self.slug}" - url += "?verifier=#{self.eportfolio.uuid}" if opts[:private] + entry.updated = updated_at + entry.published = created_at + url = "http://#{HostUrl.default_host}/eportfolios/#{eportfolio_id}/#{eportfolio_category.slug}/#{slug}" + url += "?verifier=#{eportfolio.uuid}" if opts[:private] entry.links << Atom::Link.new(:rel => 'alternate', :href => url) - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime("%Y-%m-%d")}:/eportfoli_entries/#{self.feed_code}_#{self.created_at.strftime("%Y-%m-%d-%H-%M") rescue "none"}" + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime("%Y-%m-%d")}:/eportfoli_entries/#{feed_code}_#{created_at.strftime("%Y-%m-%d-%H-%M") rescue "none"}" rendered_content = t(:click_through, "Click to view page content") entry.content = Atom::Content::Html.new(rendered_content) end diff --git a/app/models/epub_export.rb b/app/models/epub_export.rb index ac1e1129dcc67..05fa6fffb635d 100644 --- a/app/models/epub_export.rb +++ b/app/models/epub_export.rb @@ -43,7 +43,7 @@ class EpubExport < ActiveRecord::Base def update_progress_from_content_export!(val) multiplier = PERCENTAGE_COMPLETE[:exported].to_f / 100 n = val * multiplier - self.job_progress.update_completion!(n.to_i) + job_progress.update_completion!(n.to_i) end workflow do @@ -104,7 +104,7 @@ def update_progress_from_content_export!(val) given do |user| ['generated', 'failed'].include?(workflow_state) && - self.grants_right?(user, :create) + grants_right?(user, :create) end can :regenerate end @@ -158,7 +158,7 @@ def mark_as_failed(error = nil) # Epub Exportable overrides def content_cartridge - self.content_export.attachment + content_export.attachment end def self.fail_stuck_epub_exports(exports) @@ -190,7 +190,7 @@ def create_attachment_from_path!(file_path) file_path, mime_type.try(:content_type) ) - attachment = self.attachments.new + attachment = attachments.new attachment.filename = File.basename(file_path) Attachments::Storage.store_for_attachment(attachment, file) attachment.save! @@ -206,7 +206,7 @@ def cleanup_file_path!(file_path) end def sort_by_content_type? - self.course.organize_epub_by_content_type + course.organize_epub_by_content_type end private diff --git a/app/models/error_report.rb b/app/models/error_report.rb index a09f20f47fcef..6a20ceacf659f 100644 --- a/app/models/error_report.rb +++ b/app/models/error_report.rb @@ -173,7 +173,7 @@ def assign_data(data = {}) self.data ||= {} data.each do |k, v| if respond_to?(:"#{k}=") && !ErrorReport::PROTECTED_FIELDS.include?(k.to_sym) - self.send(:"#{k}=", v) + send(:"#{k}=", v) else # dup'ing because some strings come in from Rack as frozen sometimes, # depending on the web server, and our invalid utf-8 stripping breaks on that @@ -210,8 +210,8 @@ def safe_url? end def guess_email - self.email = nil if self.email && self.email.empty? - self.email ||= self.user.email rescue nil + self.email = nil if email && email.empty? + self.email ||= user.email rescue nil unless self.email domain = HostUrl.outgoing_email_domain.gsub(/[^a-zA-Z0-9]/, '-') # example.com definitely won't exist @@ -223,7 +223,7 @@ def guess_email # delete old error reports before a given date # returns the number of destroyed error reports def self.destroy_error_reports(before_date) - self.where("created_at short_url) : self.url) + short_url = (url || "").split("/")[0, 3].join("/") + title || (short ? t(:short_feed_title, "%{short_url} feed", :short_url => short_url) : url) end def header_match=(str) @@ -63,16 +63,16 @@ def header_match=(str) def destroy_entries_and_unlink_topics external_feed_entries.in_batches(of: 100).delete_all - while self.discussion_topics.limit(100).update_all(:external_feed_id => nil) > 0; end + while discussion_topics.limit(100).update_all(:external_feed_id => nil) > 0; end end def inactive? - !self.context || self.context.root_account.deleted? || self.context.inactive? + !context || context.root_account.deleted? || context.inactive? end def add_rss_entries(rss) items = rss.items.filter_map { |item| add_entry(item, rss, :rss) } - self.context.add_aggregate_entries(items, self) if self.context.respond_to?(:add_aggregate_entries) + context.add_aggregate_entries(items, self) if context.respond_to?(:add_aggregate_entries) items end @@ -80,17 +80,17 @@ def add_atom_entries(atom) items = [] atom.each_entry { |item| items << add_entry(item, atom, :atom) } items.compact! - self.context.add_aggregate_entries(items, self) if self.context.respond_to?(:add_aggregate_entries) + context.add_aggregate_entries(items, self) if context.respond_to?(:add_aggregate_entries) items end def format_description(desc) desc = (desc || "").to_s - case self.verbosity + case verbosity when 'link_only' "" when 'truncate' - self.extend TextHelper + extend TextHelper truncate_html(desc, :max_length => 250) else desc @@ -106,8 +106,8 @@ def add_entry(item, feed, feed_type) end uuid ||= Digest::SHA256.hexdigest("#{item.title}#{item.date.strftime('%Y-%m-%d')}") - entry = self.external_feed_entries.where(uuid: uuid).first - entry ||= self.external_feed_entries.where(url: item.link).first + entry = external_feed_entries.where(uuid: uuid).first + entry ||= external_feed_entries.where(url: item.link).first description = entry&.message if !description || description.empty? description = "#{ERB::Util.h(t(:original_article, "Original article"))}

" @@ -122,26 +122,26 @@ def add_entry(item, feed, feed_type) return entry end date = (item.respond_to?(:date) && item.date) || Time.zone.today - return nil if self.header_match && !item.title.downcase.include?(self.header_match.downcase) - return nil if (date && self.created_at > date rescue false) + return nil if header_match && !item.title.downcase.include?(header_match.downcase) + return nil if (date && created_at > date rescue false) description = "#{ERB::Util.h(t(:original_article, "Original article"))}

" description += format_description(item.description || item.title) - entry = self.external_feed_entries.new( + entry = external_feed_entries.new( :title => item.title.to_s, :message => description, :source_name => feed.channel.title, :source_url => feed.channel.link, :posted_at => Time.parse(date.to_s), - :user => self.user, + :user => user, :url => item.link, :uuid => uuid ) return entry if entry.save when :atom uuid = item.id || Digest::SHA256.hexdigest("#{item.title}#{item.published.utc.strftime('%Y-%m-%d')}") - entry = self.external_feed_entries.where(uuid: uuid).first - entry ||= self.external_feed_entries.where(url: item.links.alternate.to_s).first + entry = external_feed_entries.where(uuid: uuid).first + entry ||= external_feed_entries.where(url: item.links.alternate.to_s).first author = item.authors.first || OpenObject.new description = entry&.message if !description || description.empty? @@ -159,19 +159,19 @@ def add_entry(item, feed, feed_type) ) return entry end - return nil if self.header_match && !item.title.downcase.include?(self.header_match.downcase) - return nil if (item.published && self.created_at > item.published rescue false) + return nil if header_match && !item.title.downcase.include?(header_match.downcase) + return nil if (item.published && created_at > item.published rescue false) description = "#{ERB::Util.h(t(:original_article, "Original article"))}

" description += format_description(item.content || item.title) - entry = self.external_feed_entries.new( + entry = external_feed_entries.new( :title => item.title, :message => description, :source_name => feed.title.to_s, :source_url => feed.links.alternate.to_s, :posted_at => item.published, :url => item.links.alternate.to_s, - :user => self.user, + :user => user, :author_name => author.name, :author_url => author.uri, :author_email => author.email, diff --git a/app/models/external_feed_entry.rb b/app/models/external_feed_entry.rb index 037efdcf75aa1..0cff64dc918e3 100644 --- a/app/models/external_feed_entry.rb +++ b/app/models/external_feed_entry.rb @@ -42,8 +42,8 @@ def infer_defaults protected :infer_defaults def update_feed_attributes(opts) - self.update(opts) - @feed_entry_updated = self.changed? + update(opts) + @feed_entry_updated = changed? end def entry_changed? diff --git a/app/models/external_integration_key.rb b/app/models/external_integration_key.rb index d8940ef1be850..af6b851e8aa3c 100644 --- a/app/models/external_integration_key.rb +++ b/app/models/external_integration_key.rb @@ -25,7 +25,7 @@ class ExternalIntegrationKey < ActiveRecord::Base validates :context_type, presence: true validates :key_type, presence: true validates :key_value, presence: true - validates :key_type, inclusion: { in: proc { self.key_types } } + validates :key_type, inclusion: { in: proc { key_types } } validates :key_type, uniqueness: { scope: [:context_type, :context_id] } def key_type @@ -47,10 +47,10 @@ def grants_right_for?(user, sought_right) end set_policy do - given { |user| self.grants_right_for?(user, :read) } + given { |user| grants_right_for?(user, :read) } can :read - given { |user| self.grants_right_for?(user, :write) } + given { |user| grants_right_for?(user, :write) } can :write end diff --git a/app/models/favorite.rb b/app/models/favorite.rb index 4689091ada398..f9d2360103ea4 100644 --- a/app/models/favorite.rb +++ b/app/models/favorite.rb @@ -32,6 +32,6 @@ def touch_user end def populate_root_account_id - self.root_account = self.context.root_account + self.root_account = context.root_account end end diff --git a/app/models/feature_flag.rb b/app/models/feature_flag.rb index 05756c819e424..bdb05292f1e14 100644 --- a/app/models/feature_flag.rb +++ b/app/models/feature_flag.rb @@ -113,15 +113,15 @@ def audit_log_destroy end def prior_flag_state(operation) - operation == :create ? self.default_for_flag : self.state_in_database + operation == :create ? default_for_flag : state_in_database end def post_flag_state(operation) - operation == :destroy ? self.default_for_flag : self.state + operation == :destroy ? default_for_flag : state end def default_for_flag - Feature.definitions[self.feature]&.state || 'undefined' + Feature.definitions[feature]&.state || 'undefined' end private @@ -141,6 +141,6 @@ def feature_applies end def check_cache - clear_cache if self.changed? + clear_cache if changed? end end diff --git a/app/models/folder.rb b/app/models/folder.rb index 72a98985f56d8..dbde25445cee2 100644 --- a/app/models/folder.rb +++ b/app/models/folder.rb @@ -61,27 +61,27 @@ def self.name_order_by_clause(table = nil) after_commit :clear_permissions_cache, if: -> { [:workflow_state, :parent_folder_id, :locked, :lock_at, :unlock_at].any? { |k| saved_changes.key?(k) } } def file_attachments_visible_to(user) - if self.context.grants_any_right?(user, *RoleOverride::GRANULAR_FILE_PERMISSIONS) || - self.grants_right?(user, :read_as_admin) - self.active_file_attachments + if context.grants_any_right?(user, *RoleOverride::GRANULAR_FILE_PERMISSIONS) || + grants_right?(user, :read_as_admin) + active_file_attachments else - self.visible_file_attachments.not_locked + visible_file_attachments.not_locked end end def populate_root_account_id - self.root_account_id = if self.context_type == "User" + self.root_account_id = if context_type == "User" 0 elsif context_type == 'Account' && context.root_account? - self.context_id + context_id else - self.context.root_account_id + context.root_account_id end end def protect_root_folder_name - if self.parent_folder_id.blank? && self.name != Folder.root_folder_name_for_context(context) - if self.new_record? + if parent_folder_id.blank? && name != Folder.root_folder_name_for_context(context) + if new_record? root_folder = Folder.root_folders(context).first self.parent_folder_id = root_folder.id true @@ -93,7 +93,7 @@ def protect_root_folder_name end def reject_recursive_folder_structures - return true unless self.parent_folder_id_changed? + return true unless parent_folder_id_changed? seen_folders = Set.new([self]) folder = self @@ -109,7 +109,7 @@ def reject_recursive_folder_structures end def restrict_submission_folder_context - if self.for_submissions? && !self.context.is_a?(User) && !self.context.is_a?(Group) + if for_submissions? && !context.is_a?(User) && !context.is_a?(Group) errors.add(:submission_context_code, t("submissions folders must be created in User or Group context")) return false end @@ -125,10 +125,10 @@ def restrict_submission_folder_context alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.active_file_attachments.each(&:destroy) - self.active_sub_folders.each(&:destroy) + active_file_attachments.each(&:destroy) + active_sub_folders.each(&:destroy) self.deleted_at = Time.now.utc - self.save + save end scope :active, -> { where("folders.workflow_state<>'deleted'") } @@ -148,7 +148,7 @@ def full_name(reload = false) return read_attribute(:full_name) if !reload && read_attribute(:full_name) folder = self - names = [self.name] + names = [name] while folder.parent_folder_id folder = Folder.find(folder.parent_folder_id) # folder.parent_folder names << folder.name if folder @@ -157,33 +157,33 @@ def full_name(reload = false) end def infer_hidden_state - self.workflow_state ||= self.parent_folder.workflow_state if self.parent_folder && !self.deleted? + self.workflow_state ||= parent_folder.workflow_state if parent_folder && !deleted? end protected :infer_hidden_state def infer_full_name # TODO i18n t :default_folder_name, 'New Folder' - self.name = 'New Folder' if self.name.blank? - self.name = self.name.strip.tr('/', "_") + self.name = 'New Folder' if name.blank? + self.name = name.strip.tr('/', "_") @update_sub_folders = false - self.parent_folder_id = nil if !self.parent_folder || self.parent_folder.context != self.context || self.parent_folder_id == self.id - self.context = self.parent_folder.context if self.parent_folder - self.prevent_duplicate_name - self.full_name = self.full_name(true) - if self.parent_folder_id_changed? || !self.parent_folder_id || self.full_name_changed? || self.name_changed? + self.parent_folder_id = nil if !parent_folder || parent_folder.context != context || parent_folder_id == id + self.context = parent_folder.context if parent_folder + prevent_duplicate_name + self.full_name = full_name(true) + if parent_folder_id_changed? || !parent_folder_id || full_name_changed? || name_changed? @update_sub_folders = true end - @folder_id = self.id + @folder_id = id end protected :infer_full_name def prevent_duplicate_name - return unless self.parent_folder + return unless parent_folder - existing_folders = self.parent_folder.active_sub_folders.where('name ~* ? AND id <> ?', "^#{Regexp.quote(self.name)}(\\s\\d+)?$", self.id.to_i).pluck(:name) + existing_folders = parent_folder.active_sub_folders.where('name ~* ? AND id <> ?', "^#{Regexp.quote(name)}(\\s\\d+)?$", id.to_i).pluck(:name) - return unless existing_folders.include?(self.name) + return unless existing_folders.include?(name) iterations, usable_iterator, candidate = [], nil, 2 @@ -202,14 +202,14 @@ def prevent_duplicate_name end usable_iterator ||= existing_folders.size + 1 - self.name = "#{self.name} #{usable_iterator}" + self.name = "#{name} #{usable_iterator}" end protected :prevent_duplicate_name def update_sub_folders return unless @update_sub_folders - self.sub_folders.each { |f| + sub_folders.each { |f| f.reload f.full_name = f.full_name(true) f.save @@ -222,21 +222,21 @@ def clean_up_children def subcontent(opts = {}) res = [] - res += self.active_sub_folders - res += self.active_file_attachments unless opts[:exclude_files] + res += active_sub_folders + res += active_file_attachments unless opts[:exclude_files] res end def visible? return @visible if defined?(@visible) - @visible = (self.workflow_state == "visible") && (!self.parent_folder || self.parent_folder.visible?) + @visible = (self.workflow_state == "visible") && (!parent_folder || parent_folder.visible?) end def hidden? return @hidden if defined?(@hidden) - @hidden = self.workflow_state == 'hidden' || self.parent_folder&.hidden? + @hidden = self.workflow_state == 'hidden' || parent_folder&.hidden? end def hidden @@ -254,7 +254,7 @@ def just_hide def public? return @public if defined?(@public) - @public = self.workflow_state == 'public' || self.parent_folder&.public? + @public = self.workflow_state == 'public' || parent_folder&.public? end def mime_class @@ -263,32 +263,32 @@ def mime_class # true if there are any active files or folders def has_contents? - self.active_file_attachments.any? || self.active_sub_folders.any? + active_file_attachments.any? || active_sub_folders.any? end attr_accessor :clone_updated def clone_for(context, dup = nil, options = {}) - if !self.cloned_item && !self.new_record? + if !cloned_item && !new_record? self.cloned_item ||= ClonedItem.create(:original_item => self) - self.save! + save! end existing = context.folders.active.where(id: self).first - existing ||= context.folders.active.where(cloned_item_id: self.cloned_item_id || 0).first + existing ||= context.folders.active.where(cloned_item_id: cloned_item_id || 0).first return existing if existing && !options[:overwrite] && !options[:force_copy] dup ||= Folder.new dup = existing if existing && options[:overwrite] - self.attributes.except("id", "full_name", "parent_folder_id").each do |key, val| + attributes.except("id", "full_name", "parent_folder_id").each do |key, val| dup.send("#{key}=", val) end - if self.unique_type && context.folders.active.where(:unique_type => self.unique_type).exists? + if unique_type && context.folders.active.where(:unique_type => unique_type).exists? dup.unique_type = nil # we'll just copy the folder as a normal one and leave the existing unique_type'd one alone end dup.context = context if options[:include_subcontent] != false dup.save! - self.subcontent.each do |item| + subcontent.each do |item| if options[:everything] || options[:all_files] || options[item.asset_string.to_sym] case item when Attachment @@ -309,7 +309,7 @@ def clone_for(context, dup = nil, options = {}) end def root_folder? - !self.parent_folder_id + !parent_folder_id end def self.root_folder_name_for_context(context) @@ -480,60 +480,60 @@ def self.resolve_path(context, path, include_hidden_and_locked = true) def locked? return @locked if defined?(@locked) - @locked = self.locked || - (self.lock_at && Time.zone.now > self.lock_at) || - (self.unlock_at && Time.zone.now < self.unlock_at) || - self.parent_folder&.locked? + @locked = locked || + (lock_at && Time.zone.now > lock_at) || + (unlock_at && Time.zone.now < unlock_at) || + parent_folder&.locked? end def for_student_annotation_documents? - self.unique_type == Folder::STUDENT_ANNOTATION_DOCUMENTS_UNIQUE_TYPE + unique_type == Folder::STUDENT_ANNOTATION_DOCUMENTS_UNIQUE_TYPE end def for_submissions? - !self.submission_context_code.nil? + !submission_context_code.nil? end def currently_locked - self.locked || (self.lock_at && Time.zone.now > self.lock_at) || (self.unlock_at && Time.zone.now < self.unlock_at) || self.workflow_state == 'hidden' + locked || (lock_at && Time.zone.now > lock_at) || (unlock_at && Time.zone.now < unlock_at) || self.workflow_state == 'hidden' end alias_method :currently_locked?, :currently_locked set_policy do - given { |user, session| self.visible? && self.context.grants_right?(user, session, :read) } + given { |user, session| visible? && context.grants_right?(user, session, :read) } can :read - given { |user, session| self.context.grants_right?(user, session, :read_as_admin) } + given { |user, session| context.grants_right?(user, session, :read_as_admin) } can :read_as_admin, :read_contents, :read_contents_for_export given do |user, session| - self.visible? && !self.locked? && self.context.grants_right?(user, session, :read) && - !(self.context.is_a?(Course) && self.context.tab_hidden?(Course::TAB_FILES)) + visible? && !locked? && context.grants_right?(user, session, :read) && + !(context.is_a?(Course) && context.tab_hidden?(Course::TAB_FILES)) end can :read_contents, :read_contents_for_export given do |user, session| - self.visible? && !self.locked? && self.context.grants_right?(user, session, :read) + visible? && !locked? && context.grants_right?(user, session, :read) end can :read_contents_for_export given do |user, session| - self.context.grants_any_right?(user, session, :manage_files_add, :manage_files_delete, :manage_files_edit) + context.grants_any_right?(user, session, :manage_files_add, :manage_files_delete, :manage_files_edit) end can :read and can :read_contents given do |user, session| - !self.for_submissions? && self.context.grants_right?(user, session, :manage_files_add) + !for_submissions? && context.grants_right?(user, session, :manage_files_add) end can :create and can :manage_contents given do |user, session| - !self.for_submissions? && self.context.grants_right?(user, session, :manage_files_edit) + !for_submissions? && context.grants_right?(user, session, :manage_files_edit) end can :update and can :manage_contents given do |user, session| - !self.for_submissions? && self.context.grants_right?(user, session, :manage_files_delete) + !for_submissions? && context.grants_right?(user, session, :manage_files_delete) end can :delete and can :manage_contents end diff --git a/app/models/google_docs_collaboration.rb b/app/models/google_docs_collaboration.rb index bd03f3bf87279..bf3e8ce823fcc 100644 --- a/app/models/google_docs_collaboration.rb +++ b/app/models/google_docs_collaboration.rb @@ -30,17 +30,17 @@ def service_name end def delete_document - if self.document_id && self.user + if document_id && user # google docs expected an object # drive just wants an id - doc = self.document_id + doc = document_id google_adapter_for_user.delete_doc(doc) end end def initialize_document - if !self.document_id && self.user - name = self.title + if !document_id && user + name = title name = nil if name && name.empty? name ||= I18n.t('lib.google_docs.default_document_name', "Instructure Doc") @@ -61,17 +61,17 @@ def user_can_access_document_type?(user) end def authorize_user(user) - return unless self.document_id + return unless document_id service_user_id = google_adapter_user_service(user).service_user_id rescue nil - collaborator = self.collaborators.where(user_id: user).first + collaborator = collaborators.where(user_id: user).first if collaborator if collaborator.authorized_service_user_id != service_user_id - google_adapter_for_user.acl_remove(self.document_id, [collaborator.authorized_service_user_id]) if collaborator.authorized_service_user_id + google_adapter_for_user.acl_remove(document_id, [collaborator.authorized_service_user_id]) if collaborator.authorized_service_user_id user_param = service_user_id - google_adapter_for_user.acl_add(self.document_id, [user_param]) + google_adapter_for_user.acl_add(document_id, [user_param]) collaborator.update(:authorized_service_user_id => service_user_id) end else @@ -85,7 +85,7 @@ def remove_users_from_document(users_to_remove) user_service = google_user_service(user, GOOGLE_DRIVE_SERVICE) and user_service.service_user_id end - google_adapter_for_user.acl_remove(self.document_id, users_to_remove) if self.document_id + google_adapter_for_user.acl_remove(document_id, users_to_remove) if document_id end def add_users_to_document(new_users) @@ -100,12 +100,12 @@ def add_users_to_document(new_users) google_user_service(user, GOOGLE_DRIVE_SERVICE).service_user_id rescue nil end - google_adapter_for_user.acl_add(self.document_id, user_ids, domain) + google_adapter_for_user.acl_add(document_id, user_ids, domain) end end def parse_data - @entry_data ||= JSON.parse(self.data) + @entry_data ||= JSON.parse(data) end def self.config @@ -125,8 +125,8 @@ def google_user_service(user, service_domain = GOOGLE_DRIVE_SERVICE) end def google_drive_for_user - refresh_token, access_token = Rails.cache.fetch(['google_drive_tokens', self.user].cache_key) do - service = self.user.user_services.where(service: "google_drive").first + refresh_token, access_token = Rails.cache.fetch(['google_drive_tokens', user].cache_key) do + service = user.user_services.where(service: "google_drive").first service && [service.token, service.secret] end raise GoogleDrive::NoTokenError unless refresh_token && access_token diff --git a/app/models/grading_period.rb b/app/models/grading_period.rb index ec4dd748929cf..1ed3c6bf6e538 100644 --- a/app/models/grading_period.rb +++ b/app/models/grading_period.rb @@ -68,7 +68,7 @@ class GradingPeriod < ActiveRecord::Base end def self.date_in_closed_grading_period?(course:, date:, periods: nil) - period = self.for_date_in_course(date: date, course: course, periods: periods) + period = for_date_in_course(date: date, course: course, periods: periods) period.present? && period.closed? end @@ -156,7 +156,7 @@ def skip_not_overlapping_validator def self.json_for(context, user) periods = self.for(context).sort_by(&:start_date) - self.periods_json(periods, user) + periods_json(periods, user) end def self.periods_json(periods, user) diff --git a/app/models/grading_period_group.rb b/app/models/grading_period_group.rb index c7642ed12647c..92a7dd9860528 100644 --- a/app/models/grading_period_group.rb +++ b/app/models/grading_period_group.rb @@ -95,7 +95,7 @@ def recompute_course_scores end def weighted_actually_changed? - !self.new_record? && saved_change_to_weighted? + !new_record? && saved_change_to_weighted? end def recache_grading_period diff --git a/app/models/grading_standard.rb b/app/models/grading_standard.rb index a993d0e7d8e72..6fc8e49e212b4 100644 --- a/app/models/grading_standard.rb +++ b/app/models/grading_standard.rb @@ -69,7 +69,7 @@ class GradingStandard < ActiveRecord::Base VERSION = 2 set_policy do - given { |user| self.context.grants_right?(user, :manage_grades) } + given { |user| context.grants_right?(user, :manage_grades) } can :manage end @@ -143,9 +143,9 @@ def data=(new_val) end def data - unless self.version == VERSION + unless version == VERSION data = read_attribute(:data) - data = GradingStandard.upgrade_data(data, self.version) unless data.nil? + data = GradingStandard.upgrade_data(data, version) unless data.nil? self.data = data end read_attribute(:data) @@ -174,17 +174,15 @@ def trim_whitespace private :trim_whitespace def update_usage_count - self.usage_count = self.assignments.active.count - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" rescue nil + self.usage_count = assignments.active.count + self.context_code = "#{context_type.underscore}_#{context_id}" rescue nil end def assessed_assignment? - self.assignments.active.joins(:submissions).where("submissions.workflow_state='graded'").exists? + assignments.active.joins(:submissions).where("submissions.workflow_state='graded'").exists? end - def context_name - self.context.name - end + delegate :name, to: :context, prefix: true def update_data(params) self.data = params.to_a.sort_by { |_, lower_bound| lower_bound }.reverse @@ -192,8 +190,8 @@ def update_data(params) def display_name res = "" - res += self.user.name + ", " rescue "" - res += self.context.name rescue "" + res += user.name + ", " rescue "" + res += context.name rescue "" res = t("unknown_grading_details", "Unknown Details") if res.empty? res end @@ -201,12 +199,12 @@ def display_name alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.save + save end def grading_scheme res = {} - self.data.sort_by { |_, lower_bound| lower_bound }.reverse_each do |grade_name, lower_bound| + data.sort_by { |_, lower_bound| lower_bound }.reverse_each do |grade_name, lower_bound| res[grade_name] = lower_bound.to_f end res @@ -222,9 +220,9 @@ def standard_data=(params = {}) end def valid_grading_scheme_data - self.errors.add(:data, 'grading scheme values cannot be negative') if self.data.present? && self.data.any? { |v| v[1] < 0 } - self.errors.add(:data, 'grading scheme cannot contain duplicate values') if self.data.present? && self.data.map { |v| v[1] } != self.data.map { |v| v[1] }.uniq - self.errors.add(:data, 'a grading scheme name is too long') if self.data.present? && self.data.any? { |v| v[0].length > self.class.maximum_string_length } + errors.add(:data, 'grading scheme values cannot be negative') if data.present? && data.any? { |v| v[1] < 0 } + errors.add(:data, 'grading scheme cannot contain duplicate values') if data.present? && data.map { |v| v[1] } != data.map { |v| v[1] }.uniq + errors.add(:data, 'a grading scheme name is too long') if data.present? && data.any? { |v| v[0].length > self.class.maximum_string_length } end def full_range_scheme diff --git a/app/models/group.rb b/app/models/group.rb index de1fd363a4962..5f9536535c3d1 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -100,8 +100,8 @@ class Group < ActiveRecord::Base end def refresh_group_discussion_topics - if self.group_category - self.group_category.discussion_topics.active.each(&:update_subtopics) + if group_category + group_category.discussion_topics.active.each(&:update_subtopics) end end @@ -124,21 +124,21 @@ def participating_users(user_ids = nil) def participating_users_in_context(user_ids = nil, sort: false, include_inactive_users: false) users = participating_users(user_ids) users = users.order_by_sortable_name if sort - return users unless !include_inactive_users && (self.context.is_a? Course) + return users unless !include_inactive_users && (context.is_a? Course) context.participating_users(users.pluck(:id)) end def all_real_students - return self.context.all_real_students.where(users: { id: group_memberships.select(:user_id) }) if self.context.respond_to? "all_real_students" + return context.all_real_students.where(users: { id: group_memberships.select(:user_id) }) if context.respond_to? "all_real_students" - self.users + users end def all_real_student_enrollments - return self.context.all_real_student_enrollments.where(user_id: group_memberships.select(:user_id)) if self.context.respond_to? "all_real_student_enrollments" + return context.all_real_student_enrollments.where(user_id: group_memberships.select(:user_id)) if context.respond_to? "all_real_student_enrollments" - self.group_memberships + group_memberships end def wiki @@ -148,19 +148,19 @@ def wiki end def auto_accept? - self.group_category&.allows_multiple_memberships? && - self.join_level == 'parent_context_auto_join' + group_category&.allows_multiple_memberships? && + join_level == 'parent_context_auto_join' end def allow_join_request? - self.group_category&.allows_multiple_memberships? && - ['parent_context_auto_join', 'parent_context_request'].include?(self.join_level) + group_category&.allows_multiple_memberships? && + ['parent_context_auto_join', 'parent_context_request'].include?(join_level) end def allow_self_signup?(user) - self.group_category && - (self.group_category.unrestricted_self_signup? || - (self.group_category.restricted_self_signup? && self.has_common_section_with_user?(user))) + group_category && + (group_category.unrestricted_self_signup? || + (group_category.restricted_self_signup? && has_common_section_with_user?(user))) end def full? @@ -197,8 +197,8 @@ def allow_student_forum_attachments def participants(opts = {}) users = participating_users.distinct.all - if opts[:include_observers] && self.context.is_a?(Course) - (users + User.observing_students_in_course(users, self.context)).flatten.uniq + if opts[:include_observers] && context.is_a?(Course) + (users + User.observing_students_in_course(users, context)).flatten.uniq else users end @@ -209,15 +209,15 @@ def context_code end def inactive? - self.context.deleted? || (self.context.is_a?(Course) && self.context.inactive?) + context.deleted? || (context.is_a?(Course) && context.inactive?) end def context_available? - return false unless self.context + return false unless context - case self.context + case context when Course - self.context.available? && (!self.context.respond_to?(:concluded?) || !self.context.concluded?) + context.available? && (!context.respond_to?(:concluded?) || !context.concluded?) else true end @@ -228,31 +228,31 @@ def appointment_context_codes end def membership_for_user(user) - self.group_memberships.where(user_id: user).first if user + group_memberships.where(user_id: user).first if user end def has_member?(user) return nil unless user.present? - if self.group_memberships.loaded? - self.group_memberships.to_a.find { |gm| gm.accepted? && gm.user_id == user.id } + if group_memberships.loaded? + group_memberships.to_a.find { |gm| gm.accepted? && gm.user_id == user.id } else - self.participating_group_memberships.where(user_id: user).first + participating_group_memberships.where(user_id: user).first end end def has_moderator?(user) return nil unless user.present? - if self.group_memberships.loaded? - return self.group_memberships.to_a.find { |gm| gm.accepted? && gm.user_id == user.id && gm.moderator } + if group_memberships.loaded? + return group_memberships.to_a.find { |gm| gm.accepted? && gm.user_id == user.id && gm.moderator } end - self.participating_group_memberships.moderators.where(user_id: user).first + participating_group_memberships.moderators.where(user_id: user).first end def should_add_creator?(creator) - self.group_category && - (self.group_category.communities? || (self.group_category.student_organized? && self.context.user_is_student?(creator))) + group_category && + (group_category.communities? || (group_category.student_organized? && context.user_is_student?(creator))) end def submission? @@ -289,20 +289,20 @@ def self.not_in_group_sql_fragment(groups) end def active? - self.available? + available? end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - self.save + save end def restore self.workflow_state = 'available' self.deleted_at = nil - self.save! + save! end Bookmarker = BookmarkedCollection::SimpleBookmarker.new(Group, :name, :id) @@ -321,18 +321,18 @@ def potential_collaborators end def full_name - res = before_label(self.name) + " " - res += (self.context.course_code rescue self.context.name) if self.context + res = before_label(name) + " " + res += (context.course_code rescue context.name) if context res end def to_atom Atom::Entry.new do |entry| - entry.title = self.name - entry.updated = self.updated_at - entry.published = self.created_at + entry.title = name + entry.updated = updated_at + entry.published = created_at entry.links << Atom::Link.new(:rel => 'alternate', - :href => "/groups/#{self.id}") + :href => "/groups/#{id}") end end @@ -348,13 +348,13 @@ def add_user(user, new_record_state = nil, moderator = nil) member = nil GroupMembership.unique_constraint_retry do - if (member = self.group_memberships.where(user_id: user).first) + if (member = group_memberships.where(user_id: user).first) member.workflow_state = new_record_state unless member.active? # only update moderator if true/false is explicitly passed in member.moderator = moderator unless moderator.nil? member.save if member.changed? else - member = self.group_memberships.create(attrs) + member = group_memberships.create(attrs) end end # permissions for this user in the group are probably different now @@ -366,7 +366,7 @@ def set_users(users) user_ids = users.map(&:id) memberships = [] transaction do - self.group_memberships.where.not(user_id: user_ids).destroy_all + group_memberships.where.not(user_id: user_ids).destroy_all users.each do |user| memberships << invite_user(user) end @@ -386,16 +386,16 @@ def bulk_add_users_to_group(users, options = {}) return if users.empty? user_ids = users.map(&:id) - old_group_memberships = self.group_memberships.where(user_id: user_ids).to_a + old_group_memberships = group_memberships.where(user_id: user_ids).to_a bulk_insert_group_memberships(users, options) - all_group_memberships = self.group_memberships.where(user_id: user_ids) + all_group_memberships = group_memberships.where(user_id: user_ids) new_group_memberships = all_group_memberships - old_group_memberships new_group_memberships.sort_by!(&:user_id) users.sort_by!(&:id) User.clear_cache_keys(user_ids, :groups) users.each { |user| clear_permissions_cache(user) } - if self.context_available? + if context_available? notification_name = options[:notification_name] || "New Context Group Membership" notification = BroadcastPolicy.notification_finder.by_name(notification_name) @@ -416,12 +416,12 @@ def bulk_add_users_to_group(users, options = {}) def bulk_insert_group_memberships(users, options = {}) current_time = Time.now options = { - :group_id => self.id, + :group_id => id, :workflow_state => 'accepted', :moderator => false, :created_at => current_time, :updated_at => current_time, - :root_account_id => self.root_account_id + :root_account_id => root_account_id }.merge(options) GroupMembership.bulk_insert(users.map { |user| options.merge({ :user_id => user.id, :uuid => CanvasSlug.generate_securish_uuid }) @@ -429,35 +429,35 @@ def bulk_insert_group_memberships(users, options = {}) end def invite_user(user) - self.add_user(user, 'invited') + add_user(user, 'invited') end def request_user(user) - self.add_user(user, 'requested') + add_user(user, 'requested') end def invitees=(params) invitees = [] (params || {}).each do |key, val| - if self.context - invitees << self.context.users.where(id: key.to_i).first if val != '0' + if context + invitees << context.users.where(id: key.to_i).first if val != '0' else invitees << User.where(id: key.to_i).first if val != '0' end end - invitees.compact.filter_map { |i| self.invite_user(i) } + invitees.compact.filter_map { |i| invite_user(i) } end def peer_groups - return [] if !self.context || !self.group_category || self.group_category.allows_multiple_memberships? + return [] if !context || !group_category || group_category.allows_multiple_memberships? - self.group_category.groups.where("id<>?", self).to_a + group_category.groups.where("id<>?", self).to_a end def ensure_defaults self.name ||= CanvasSlug.generate_securish_uuid self.uuid ||= CanvasSlug.generate_securish_uuid - self.group_category ||= GroupCategory.student_organized_for(self.context) + self.group_category ||= GroupCategory.student_organized_for(context) self.join_level ||= 'invitation_only' self.is_public ||= false self.is_public = false unless self.group_category.try(:communities?) @@ -466,11 +466,11 @@ def ensure_defaults private :ensure_defaults def set_default_account - case self.context + case context when Course - self.account = self.context.account + self.account = context.account when Account - self.account = self.context + self.account = context end end @@ -481,8 +481,8 @@ def account=(new_account) def account_id=(new_account_id) write_attribute(:account_id, new_account_id) - if self.account_id_changed? - self.root_account = self.reload_account&.root_account + if account_id_changed? + self.root_account = reload_account&.root_account end end @@ -490,7 +490,7 @@ def account_id=(new_account_id) # permission check for efficiency -- see User#cached_contexts set_policy do # Participate means the user is connected to the group somehow and can be - given { |user| user && can_participate?(user) && self.has_member?(user) } + given { |user| user && can_participate?(user) && has_member?(user) } can :participate and can :manage_calendar and can :manage_content and @@ -508,10 +508,10 @@ def account_id=(new_account_id) # group, the student must be able to :participate, and the teacher should be able to add students while the course # is unpublished and therefore unreadable to said students) unless their containing context can be read by the user # in question - given { |user, session| self.context.is_a?(Account) || self.context.grants_right?(user, session, :read) } + given { |user, session| context.is_a?(Account) || context.grants_right?(user, session, :read) } use_additional_policy do - given { |user| user && self.has_member?(user) } + given { |user| user && has_member?(user) } can :read_forum and can :read and can :read_announcements and @@ -519,17 +519,17 @@ def account_id=(new_account_id) can :view_unpublished_items given { |user, session| - user && self.has_member?(user) && - (!self.context || self.context.is_a?(Account) || self.context.grants_any_right?(user, session, :send_messages, :send_messages_all)) + user && has_member?(user) && + (!context || context.is_a?(Account) || context.grants_any_right?(user, session, :send_messages, :send_messages_all)) } can :send_messages and can :send_messages_all # if I am a member of this group and I can moderate_forum in the group's context # (makes it so group members cant edit each other's discussion entries) - given { |user, session| user && self.has_member?(user) && (!self.context || self.context.grants_right?(user, session, :moderate_forum)) } + given { |user, session| user && has_member?(user) && (!context || context.grants_right?(user, session, :moderate_forum)) } can :moderate_forum - given { |user| user && self.has_moderator?(user) } + given { |user| user && has_moderator?(user) } can :delete and can :manage and can :manage_admin_users and @@ -538,23 +538,23 @@ def account_id=(new_account_id) can :moderate_forum and can :update - given { |user| user && self.leader == user } + given { |user| user && leader == user } can :update given { group_category.try(:communities?) } can :create - given { |user, session| self.context&.grants_right?(user, session, :participate_as_student) } + given { |user, session| context&.grants_right?(user, session, :participate_as_student) } can :participate_as_student - given { |user, session| self.grants_right?(user, session, :participate_as_student) && self.context.allow_student_organized_groups } + given { |user, session| grants_right?(user, session, :participate_as_student) && context.allow_student_organized_groups } can :create #################### Begin legacy permission block ######################### given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && - self.context.grants_right?(user, session, :manage_groups) + !context.root_account.feature_enabled?(:granular_permissions_manage_groups) && + context.grants_right?(user, session, :manage_groups) end can :create and can :create_collaborations and can :delete and can :manage and can :manage_admin_users and can :allow_course_admin_actions and can :manage_calendar and @@ -568,15 +568,15 @@ def account_id=(new_account_id) ##################### End legacy permission block ########################## given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && - self.context.grants_right?(user, session, :manage_groups_add) + context.root_account.feature_enabled?(:granular_permissions_manage_groups) && + context.grants_right?(user, session, :manage_groups_add) end can :read and can :create # permissions to update a group and manage actions within the context of a group given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && - self.context.grants_right?(user, session, :manage_groups_manage) + context.root_account.feature_enabled?(:granular_permissions_manage_groups) && + context.grants_right?(user, session, :manage_groups_manage) end can :read and can :update and can :create_collaborations and can :manage and can :manage_admin_users and can :allow_course_admin_actions and can :manage_calendar and @@ -588,18 +588,18 @@ def account_id=(new_account_id) can :send_messages_all and can :view_unpublished_items given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && - self.context.grants_right?(user, session, :manage_groups_delete) + context.root_account.feature_enabled?(:granular_permissions_manage_groups) && + context.grants_right?(user, session, :manage_groups_delete) end can :read and can :delete - given { |user, session| self.context&.grants_all_rights?(user, session, :read_as_admin, :post_to_forum) } + given { |user, session| context&.grants_all_rights?(user, session, :read_as_admin, :post_to_forum) } can :post_to_forum - given { |user, session| self.context&.grants_all_rights?(user, session, :read_as_admin, :create_forum) } + given { |user, session| context&.grants_all_rights?(user, session, :read_as_admin, :create_forum) } can :create_forum - given { |user, session| self.context&.grants_right?(user, session, :view_group_pages) } + given { |user, session| context&.grants_right?(user, session, :view_group_pages) } can :read and can :read_forum and can :read_announcements and can :read_roster # Join is participate + the group being in a state that allows joining directly (free_association) @@ -609,19 +609,19 @@ def account_id=(new_account_id) given { |user| user && (self.group_category.try(:allows_multiple_memberships?) || allow_self_signup?(user)) } can :leave - given { |user, session| self.grants_right?(user, session, :manage_content) && self.context && self.context.grants_right?(user, session, :create_conferences) } + given { |user, session| grants_right?(user, session, :manage_content) && context && context.grants_right?(user, session, :create_conferences) } can :create_conferences - given { |user, session| self.context&.grants_right?(user, session, :read_as_admin) } + given { |user, session| context&.grants_right?(user, session, :read_as_admin) } can :read_as_admin - given { |user, session| self.context&.grants_right?(user, session, :read_sis) } + given { |user, session| context&.grants_right?(user, session, :read_sis) } can :read_sis - given { |user, session| self.context&.grants_right?(user, session, :view_user_logins) } + given { |user, session| context&.grants_right?(user, session, :view_user_logins) } can :view_user_logins - given { |user, session| self.context&.grants_right?(user, session, :read_email_addresses) } + given { |user, session| context&.grants_right?(user, session, :read_email_addresses) } can :read_email_addresses end end @@ -635,29 +635,29 @@ def users_visible_to(user, opts = {}) # Helper needed by several permissions, use grants_right?(user, :participate) def can_participate?(user) return true if can_participate - return false unless user.present? && self.context.present? + return false unless user.present? && context.present? return true if self.group_category.try(:communities?) - case self.context + case context when Course - return self.context.enrollments.not_fake.where(:user_id => user.id).active_by_date.exists? + return context.enrollments.not_fake.where(:user_id => user.id).active_by_date.exists? when Account - return self.context.root_account.user_account_associations.where(:user_id => user.id).exists? + return context.root_account.user_account_associations.where(:user_id => user.id).exists? end false end def can_join?(user) - if self.context.is_a?(Course) - self.context.enrollments.not_fake.except(:preload).where(:user_id => user.id).exists? + if context.is_a?(Course) + context.enrollments.not_fake.except(:preload).where(:user_id => user.id).exists? else can_participate?(user) end end def user_can_manage_own_discussion_posts?(user) - return true unless self.context.is_a?(Course) + return true unless context.is_a?(Course) context.user_can_manage_own_discussion_posts?(user) end @@ -668,22 +668,22 @@ def is_a_context? def members_json_cached Rails.cache.fetch(['group_members_json', self].cache_key) do - self.users.map { |u| u.group_member_json(self.context) } + users.map { |u| u.group_member_json(context) } end end def members_count_cached Rails.cache.fetch(['group_members_count', self].cache_key) do - self.members_json_cached.length + members_json_cached.length end end def members_count - self.participating_group_memberships.count + participating_group_memberships.count end def quota - self.storage_quota || self.account.default_group_storage_quota || self.class.default_storage_quota + storage_quota || account.default_group_storage_quota || self.class.default_storage_quota end def self.default_storage_quota @@ -711,7 +711,7 @@ def tabs_available(user = nil, **) { :id => TAB_FILES, :label => t("#group.tabs.files", "Files"), :css_class => 'files', :href => :group_files_path }, ] - if user && self.grants_right?(user, :read) + if user && grants_right?(user, :read) available_tabs << { :id => TAB_CONFERENCES, :label => WebConference.conference_tab_name, :css_class => 'conferences', :href => :group_conferences_path } available_tabs << { :id => TAB_COLLABORATIONS, :label => t('#tabs.collaborations', "Collaborations"), :css_class => 'collaborations', :href => :group_collaborations_path } available_tabs << { :id => TAB_COLLABORATIONS_NEW, :label => t('#tabs.collaborations', "Collaborations"), :css_class => 'collaborations', :href => :group_lti_collaborations_path } @@ -729,7 +729,7 @@ def allow_media_comments? end def group_category_name - self.read_attribute(:category) + read_attribute(:category) end def maintain_category_attribute @@ -737,7 +737,7 @@ def maintain_category_attribute # exists solely for the migration that introduces the GroupCategory model). # this way group_category_name is correct if someone mistakenly uses it # (modulo category renaming in the GroupCategory model). - self.write_attribute(:category, self.group_category&.name) + write_attribute(:category, self.group_category&.name) end def as_json(options = nil) @@ -754,15 +754,15 @@ def as_json(options = nil) end def has_common_section? - self.context.is_a?(Course) && - self.context.course_sections.active.any? { |section| section.common_to_users?(self.users) } + context.is_a?(Course) && + context.course_sections.active.any? { |section| section.common_to_users?(users) } end def has_common_section_with_user?(user) - return false unless self.context.is_a?(Course) + return false unless context.is_a?(Course) - users = self.users.where(id: self.context.enrollments.active_or_pending.select(:user_id)) + [user] - self.context.course_sections.active.any? { |section| section.common_to_users?(users) } + users = self.users.where(id: context.enrollments.active_or_pending.select(:user_id)) + [user] + context.course_sections.active.any? { |section| section.common_to_users?(users) } end def self.join_levels @@ -799,7 +799,7 @@ def serialize_permissions(permissions_hash, user, session) end def content_exports_visible_to(user) - self.content_exports.where(user_id: user) + content_exports.where(user_id: user) end def account_chain(include_site_admin: false) @@ -824,8 +824,8 @@ def submissions_folder(_course = nil) return @submissions_folder if @submissions_folder Folder.unique_constraint_retry do - @submissions_folder = self.folders.where(parent_folder_id: Folder.root_folders(self).first, submission_context_code: 'root') - .first_or_create!(name: I18n.t('Submissions')) + @submissions_folder = folders.where(parent_folder_id: Folder.root_folders(self).first, submission_context_code: 'root') + .first_or_create!(name: I18n.t('Submissions')) end end diff --git a/app/models/group_and_membership_importer.rb b/app/models/group_and_membership_importer.rb index 50d07c598a98d..1d95e591098a6 100644 --- a/app/models/group_and_membership_importer.rb +++ b/app/models/group_and_membership_importer.rb @@ -64,7 +64,7 @@ def import_groups_from_attachment(progress) progress.complete progress.save! self.workflow_state = 'completed' - self.save! + save! end workflow do @@ -82,7 +82,7 @@ def validate_file(csv) def fail_import(error) self.workflow_state = 'failed' - self.save! + save! progress.message = error progress.save! progress.fail diff --git a/app/models/group_category.rb b/app/models/group_category.rb index 83217df0eb86f..cfd749cc64c0d 100644 --- a/app/models/group_category.rb +++ b/app/models/group_category.rb @@ -162,15 +162,15 @@ def role_category_for_context(role, context) end def communities? - self.role == 'communities' + role == 'communities' end def student_organized? - self.role == 'student_organized' + role == 'student_organized' end def protected? - self.role.present? && self.role != 'imported' + role.present? && role != 'imported' end # Group categories generally restrict students to only be in one group per @@ -178,7 +178,7 @@ def protected? # communities as one big group category, and then relax that membership # restriction. def allows_multiple_memberships? - self.student_organized? || self.communities? + student_organized? || communities? end # this is preferred over setting self_signup directly. know that if you set @@ -187,19 +187,19 @@ def allows_multiple_memberships? def configure_self_signup(enabled, restricted) args = { enable_self_signup: enabled, restrict_self_signup: restricted } self.self_signup = GroupCategories::Params.new(args).self_signup - self.save! + save! end def self_signup? - self.self_signup.present? + self_signup.present? end def unrestricted_self_signup? - self.self_signup.present? && self.self_signup != 'restricted' + self_signup.present? && self_signup != 'restricted' end def restricted_self_signup? - self.self_signup.present? && self.self_signup == 'restricted' + self_signup.present? && self_signup == 'restricted' end def has_heterogenous_group? @@ -207,9 +207,9 @@ def has_heterogenous_group? # condition would may any group in the category say has_common_section? # false, and force us true. so we special case it, and get the short # circuit as a bonus. - return false unless self.context.is_a?(Course) + return false unless context.is_a?(Course) - self.groups.any? { |group| !group.has_common_section? } + groups.any? { |group| !group.has_common_section? } end def group_for(user) @@ -232,13 +232,13 @@ def destroy # double checked groups.destroy_all does the right thing. :) groups.destroy_all self.deleted_at = Time.now.utc - self.save + save end def restore - self.groups.where(deleted_at: [self.deleted_at - 10.minutes..self.deleted_at]).update_all(workflow_state: 'available', deleted_at: nil) + groups.where(deleted_at: [deleted_at - 10.minutes..deleted_at]).update_all(workflow_state: 'available', deleted_at: nil) self.deleted_at = nil - self.save! + save! end # We can't reassign existing group members, groups can have different maximum limits, and we want @@ -383,10 +383,10 @@ def randomly_add_allocated_members_to_groups(members, groups, water_allocation) end def finish_group_member_assignment - return unless self.reload.groups.any? + return unless reload.groups.any? - if self.auto_leader - self.groups.each do |group| + if auto_leader + groups.each do |group| GroupLeadership.new(group).auto_assign!(auto_leader) end end @@ -400,20 +400,20 @@ def finish_group_member_assignment def distribute_members_among_groups_by_section # trying to make this work for new group sets is hard enough - i'm not even going to bother with ones with existing stuff if GroupMembership.active.where(:group_id => groups.active).exists? - self.errors.add(:group_by_section, t("Groups must be empty to assign by section")) + errors.add(:group_by_section, t("Groups must be empty to assign by section")) return end if groups.active.where.not(:max_membership => nil).exists? - self.errors.add(:group_by_section, t("Groups cannot have size restrictions to assign by section")) + errors.add(:group_by_section, t("Groups cannot have size restrictions to assign by section")) return end group_count = groups.active.count - section_count = self.context.enrollments.active_or_pending.where(:type => "StudentEnrollment").distinct.count(:course_section_id) + section_count = context.enrollments.active_or_pending.where(:type => "StudentEnrollment").distinct.count(:course_section_id) return unless group_count > 0 && section_count > 0 if group_count < section_count - self.errors.add(:create_group_count, t("Must have at least as many groups as sections to assign by section")) + errors.add(:create_group_count, t("Must have at least as many groups as sections to assign by section")) return end @@ -435,8 +435,8 @@ def create_group_member_count=(num) def set_root_account_id # context might be nil since this runs before validations. - if self.context&.root_account - root_account_id = self.context.root_account.id + if context&.root_account + root_account_id = context.root_account.id self.root_account_id = root_account_id end end @@ -450,10 +450,10 @@ def auto_create_groups if split_type InstStatsd::Statsd.increment('groups.auto_create', - tags: { split_type: split_type, root_account_id: self.root_account&.global_id, root_account_name: self.root_account&.name }) + tags: { split_type: split_type, root_account_id: root_account&.global_id, root_account_name: root_account&.name }) end - by_section = @group_by_section && self.context.is_a?(Course) + by_section = @group_by_section && context.is_a?(Course) calculate_group_count_by_membership(by_section: by_section) if @create_group_member_count create_groups(@create_group_count) if @create_group_count if @assign_unassigned_members && @create_group_count @@ -493,8 +493,8 @@ def assign_unassigned_members(by_section = false, updating_user: nil) distribute_members_among_groups_by_section finish_group_member_assignment if current_progress - if self.errors.any? - current_progress.message = self.errors.full_messages + if errors.any? + current_progress.message = errors.full_messages current_progress.fail else complete_progress @@ -541,14 +541,14 @@ def clone_groups_and_memberships(new_group_category) end def discussion_topics - self.shard.activate do - DiscussionTopic.where(context_type: self.context_type, context_id: self.context_id, group_category_id: self) + shard.activate do + DiscussionTopic.where(context_type: context_type, context_id: context_id, group_category_id: self) end end def submission_ids_by_user_id(user_ids = nil) - self.shard.activate do - assignments = Assignment.active.where(:context_type => self.context_type, :context_id => self.context_id, :group_category_id => self.id) + shard.activate do + assignments = Assignment.active.where(:context_type => context_type, :context_id => context_id, :group_category_id => id) submissions = Submission.active.where(assignment_id: assignments, workflow_state: 'submitted') submissions = submissions.where(:user_id => user_ids) if user_ids rows = submissions.pluck(:id, :user_id) diff --git a/app/models/group_membership.rb b/app/models/group_membership.rb index 60032376a5a78..efc7e419e19b6 100644 --- a/app/models/group_membership.rb +++ b/app/models/group_membership.rb @@ -64,41 +64,41 @@ def course_broadcast_data set_broadcast_policy do |p| p.dispatch :new_context_group_membership - p.to { self.user } + p.to { user } p.whenever { |record| record.just_created && record.accepted? && record.group && record.group.context_available? && - record.group&.can_participate?(self.user) && + record.group&.can_participate?(user) && record.sis_batch_id.blank? } p.data { course_broadcast_data } p.dispatch :new_context_group_membership_invitation - p.to { self.user } + p.to { user } p.whenever { |record| record.just_created && record.invited? && record.group && record.group.context_available? && - record.group&.can_participate?(self.user) && + record.group&.can_participate?(user) && record.sis_batch_id.blank? } p.data { course_broadcast_data } p.dispatch :group_membership_accepted - p.to { self.user } + p.to { user } p.whenever { |record| record.changed_state(:accepted, :requested) } p.data { course_broadcast_data } p.dispatch :group_membership_rejected - p.to { self.user } + p.to { user } p.whenever { |record| record.changed_state(:rejected, :requested) } p.data { course_broadcast_data } p.dispatch :new_student_organized_group - p.to { self.group.context.participating_admins } + p.to { group.context.participating_admins } p.whenever { |record| record.group.context.is_a?(Course) && record.just_created && @@ -116,38 +116,38 @@ def assign_uuid # auto accept 'requested' or 'invited' memberships until we implement # accepting requests/invitations def auto_join - return true if self.group.try(:group_category).try(:communities?) + return true if group.try(:group_category).try(:communities?) - self.workflow_state = 'accepted' if self.group && (self.requested? || self.invited?) + self.workflow_state = 'accepted' if group && (requested? || invited?) true end protected :auto_join def update_group_leadership - GroupLeadership.new(Group.find(self.group_id)).member_changed_event(self) + GroupLeadership.new(Group.find(group_id)).member_changed_event(self) end protected :update_group_leadership def ensure_mutually_exclusive_membership - return unless self.group - return if self.deleted? + return unless group + return if deleted? - peer_groups = self.group.peer_groups.map(&:id) - GroupMembership.active.where(:group_id => peer_groups, :user_id => self.user_id).destroy_all + peer_groups = group.peer_groups.map(&:id) + GroupMembership.active.where(:group_id => peer_groups, :user_id => user_id).destroy_all end protected :ensure_mutually_exclusive_membership def restricted_self_signup? - self.group.group_category&.restricted_self_signup? + group.group_category&.restricted_self_signup? end def has_common_section_with_me? - self.group.has_common_section_with_user?(user) + group.has_common_section_with_user?(user) end def verify_section_homogeneity_if_necessary if new_record? && restricted_self_signup? && !has_common_section_with_me? - errors.add(:user_id, t('errors.not_in_group_section', "%{student} does not share a section with the other members of %{group}.", :student => self.user.name, :group => self.group.name)) + errors.add(:user_id, t('errors.not_in_group_section', "%{student} does not share a section with the other members of %{group}.", :student => user.name, :group => group.name)) throw :abort end end @@ -163,7 +163,7 @@ def validate_within_group_limit attr_accessor :old_group_id def capture_old_group_id - self.old_group_id = self.group_id_was if self.group_id_changed? + self.old_group_id = group_id_was if group_id_changed? true end protected :capture_old_group_id @@ -188,8 +188,8 @@ def update_cached_due_dates end def touch_groups - groups_to_touch = [self.group_id] - groups_to_touch << self.old_group_id if self.old_group_id + groups_to_touch = [group_id] + groups_to_touch << old_group_id if old_group_id Group.where(:id => groups_to_touch).touch_all end protected :touch_groups @@ -213,31 +213,31 @@ def self.serialization_excludes # true iff 'active' and the pair of user and group's course match one of the # provided enrollments def active_given_enrollments?(enrollments) - accepted? && (!self.group.context.is_a?(Course) || - enrollments.any? { |e| e.user == self.user && e.course == self.group.context }) + accepted? && (!group.context.is_a?(Course) || + enrollments.any? { |e| e.user == user && e.course == group.context }) end def invalidate_user_membership_cache - self.user.clear_cache_key(:groups) + user.clear_cache_key(:groups) end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.save! + save! end set_policy do #################### Begin legacy permission block ######################### given do |user, session| - !self.group.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && - user && self.user && self.group && !self.group.group_category.try(:communities?) && + !group.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && + user && self.user && group && !group.group_category.try(:communities?) && ( - (user == self.user && self.group.grants_right?(user, session, :join)) || + (user == self.user && group.grants_right?(user, session, :join)) || ( - self.group.can_join?(self.user) && self.group.context && - self.group.context.grants_right?(user, session, :manage_groups) + group.can_join?(self.user) && group.context && + group.context.grants_right?(user, session, :manage_groups) ) ) end @@ -248,13 +248,13 @@ def destroy # for non-communities, people can be placed into groups by users who can # manage groups at the context level, but not moderators (hence :manage_groups_manage) given do |user, session| - self.group.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && - user && self.user && self.group && !self.group.group_category.try(:communities?) && + group.context.root_account.feature_enabled?(:granular_permissions_manage_groups) && + user && self.user && group && !group.group_category.try(:communities?) && ( - (user == self.user && self.group.grants_right?(user, session, :join)) || + (user == self.user && group.grants_right?(user, session, :join)) || ( - self.group.can_join?(self.user) && self.group.context && - self.group.context.grants_right?(user, session, :manage_groups_manage) + group.can_join?(self.user) && group.context && + group.context.grants_right?(user, session, :manage_groups_manage) ) ) end @@ -262,25 +262,25 @@ def destroy # for communities, users must initiate in order to be added to a group given do |user, _session| - user && self.group && user == self.user && self.group.grants_right?(user, :join) && - self.group.group_category.try(:communities?) + user && group && user == self.user && group.grants_right?(user, :join) && + group.group_category.try(:communities?) end can :create # user can read group membership if they can read its group's roster - given { |user, session| user && self.group && self.group.grants_right?(user, session, :read_roster) } + given { |user, session| user && group && group.grants_right?(user, session, :read_roster) } can :read - given { |user, session| user && self.group && self.group.grants_right?(user, session, :manage) } + given { |user, session| user && group && group.grants_right?(user, session, :manage) } can :update # allow moderators to kick people out # hence :manage instead of :manage_groups_delete on the context given do |user, session| - user && self.user && self.group && + user && self.user && group && ( - (user == self.user && self.group.grants_right?(self.user, session, :leave)) || - self.group.grants_right?(user, session, :manage) + (user == self.user && group.grants_right?(self.user, session, :leave)) || + group.grants_right?(user, session, :manage) ) end can :delete diff --git a/app/models/importers.rb b/app/models/importers.rb index b0c7f841a760b..40571259ffd02 100644 --- a/app/models/importers.rb +++ b/app/models/importers.rb @@ -47,16 +47,16 @@ class << self # forward translations to CalendarEvent; they used to live there. def translate(*args) - raise "Needs self.item_class to be set in #{self}" unless self.item_class + raise "Needs self.item_class to be set in #{self}" unless item_class - self.item_class.translate(*args) + item_class.translate(*args) end alias_method :t, :translate def logger(*args) - raise "Needs self.item_class to be set in #{self}" unless self.item_class + raise "Needs self.item_class to be set in #{self}" unless item_class - self.item_class.logger(*args) + item_class.logger(*args) end end end diff --git a/app/models/importers/assessment_question_importer.rb b/app/models/importers/assessment_question_importer.rb index 203a68939173f..f80361336fc18 100644 --- a/app/models/importers/assessment_question_importer.rb +++ b/app/models/importers/assessment_question_importer.rb @@ -119,7 +119,7 @@ def self.process_migration(data, migration) next if question['assessment_question_id'] && question_bank.edit_types_locked_for_overwrite_on_import.include?(:content) end - question = self.import_from_migration(question, migration.context, migration, question_bank) + question = import_from_migration(question, migration.context, migration, question_bank) question_data[:aq_data][question['migration_id']] = question rescue migration.add_import_warning(t('#migration.quiz_question_type', "Quiz Question"), question[:question_name], $!) @@ -140,7 +140,7 @@ def self.import_from_migration(hash, context, migration, bank, **) hash = hash.with_indifferent_access hash.delete(:question_bank_migration_id) if hash.key?(:question_bank_migration_id) - self.prep_for_import(hash, migration, :assessment_question) + prep_for_import(hash, migration, :assessment_question) import_warnings = hash.delete(:import_warnings) || [] if (error = hash.delete(:import_error)) diff --git a/app/models/importers/assignment_group_importer.rb b/app/models/importers/assignment_group_importer.rb index 88216795edde2..62607d72143a6 100644 --- a/app/models/importers/assignment_group_importer.rb +++ b/app/models/importers/assignment_group_importer.rb @@ -25,7 +25,7 @@ class AssignmentGroupImporter < Importer def self.process_migration(data, migration) AssignmentGroup.suspend_callbacks(:update_student_grades) do - self.add_groups_for_imported_assignments(data, migration) + add_groups_for_imported_assignments(data, migration) groups = data['assignment_groups'] || [] groups.each do |group| if migration.import_object?("assignment_groups", group['migration_id']) diff --git a/app/models/importers/assignment_importer.rb b/app/models/importers/assignment_importer.rb index 39813fa9e1df8..ffaa7f0702d73 100644 --- a/app/models/importers/assignment_importer.rb +++ b/app/models/importers/assignment_importer.rb @@ -129,7 +129,7 @@ def self.import_from_migration(hash, context, migration, item = nil, quiz = nil) end end if hash[:instructions_in_html] == false - self.extend TextHelper + extend TextHelper end description = "" diff --git a/app/models/importers/calendar_event_importer.rb b/app/models/importers/calendar_event_importer.rb index 22368f358d0b5..72c7aaffda5d1 100644 --- a/app/models/importers/calendar_event_importer.rb +++ b/app/models/importers/calendar_event_importer.rb @@ -71,7 +71,7 @@ def self.import_from_migration(hash, context, migration, item = nil) # no idea what 'area' or 'media_collection' attachment types are, so we're ignoring them def self.import_migration_attachment_suffix(hash, context) suffix_method_name = "#{hash[:attachment_type]}_attachment_description" - suffix = self.send(suffix_method_name, hash, context) if self.respond_to?(suffix_method_name) + suffix = send(suffix_method_name, hash, context) if respond_to?(suffix_method_name) suffix || "" end diff --git a/app/models/importers/context_external_tool_importer.rb b/app/models/importers/context_external_tool_importer.rb index 925a6e8e897b7..b2d75199d6905 100644 --- a/app/models/importers/context_external_tool_importer.rb +++ b/app/models/importers/context_external_tool_importer.rb @@ -109,11 +109,11 @@ def self.create_tool_settings(hash) end def self.check_for_compatible_tool_translation(hash, migration) - if migration.migration_settings[:prefer_existing_tools] && (tool = self.check_for_existing_tool(hash, migration)) + if migration.migration_settings[:prefer_existing_tools] && (tool = check_for_existing_tool(hash, migration)) return tool end - if migration.migration_type == "common_cartridge_importer" && (tool = self.check_for_tool_compaction(hash, migration)) + if migration.migration_type == "common_cartridge_importer" && (tool = check_for_tool_compaction(hash, migration)) tool end end @@ -121,7 +121,7 @@ def self.check_for_compatible_tool_translation(hash, migration) def self.check_for_tool_compaction(hash, migration) # rather than making a thousand separate tools, try to combine into other tools if we can - url, domain, settings = self.extract_for_translation(hash) + url, domain, settings = extract_for_translation(hash) return if url && ContextModuleImporter.add_custom_fields_to_url(url, hash[:custom_fields] || {}).nil? return unless url || domain @@ -165,7 +165,7 @@ def self.check_for_tool_compaction(hash, migration) end def self.check_for_existing_tool(hash, migration) - url, domain, settings = self.extract_for_translation(hash) + url, domain, settings = extract_for_translation(hash) return unless domain tool_contexts = ContextExternalTool.contexts_to_search(migration.context) @@ -175,7 +175,7 @@ def self.check_for_existing_tool(hash, migration) tools.each do |tool| # check if tool is compatible - next unless self.matching_settings?(migration, hash, tool, settings, true) + next unless matching_settings?(migration, hash, tool, settings, true) if tool.url.blank? && tool.domain.present? if domain && domain == tool.domain diff --git a/app/models/importers/context_module_importer.rb b/app/models/importers/context_module_importer.rb index 9de98b91b812c..39d5922e01446 100644 --- a/app/models/importers/context_module_importer.rb +++ b/app/models/importers/context_module_importer.rb @@ -46,7 +46,7 @@ def self.select_all_linked_module_items(data, migration) return if migration.import_everything? (data['modules'] || []).each do |mod| - self.select_linked_module_items(mod, migration) + select_linked_module_items(mod, migration) end end @@ -55,7 +55,7 @@ def self.select_linked_module_items(mod, migration, select_all = false) (mod['items'] || []).each do |item| if item['type'] == 'submodule' # recursively select content in submodules - self.select_linked_module_items(item, migration, true) + select_linked_module_items(item, migration, true) elsif (resource_class = linked_resource_type_class(item['linked_resource_type'])) migration.import_object!(resource_class.table_name, item['linked_resource_id']) end @@ -63,7 +63,7 @@ def self.select_linked_module_items(mod, migration, select_all = false) else (mod['items'] || []).each do |item| if item['type'] == 'submodule' - self.select_linked_module_items(item, migration) # the parent may not be selected, but a sub-module may be + select_linked_module_items(item, migration) # the parent may not be selected, but a sub-module may be end end end @@ -74,7 +74,7 @@ def self.process_migration(data, migration) migration.last_module_position = migration.context.context_modules.maximum(:position) if migration.is_a?(ContentMigration) modules.each do |mod| - self.process_module(mod, migration) + process_module(mod, migration) end migration.context.context_modules.first.try(:fix_position_conflicts) migration.context.touch @@ -83,7 +83,7 @@ def self.process_migration(data, migration) def self.process_module(mod, migration) if migration.import_object?("context_modules", mod['migration_id']) || migration.import_object?("modules", mod['migration_id']) begin - self.import_from_migration(mod, migration.context, migration) + import_from_migration(mod, migration.context, migration) rescue migration.add_import_warning(t('#migration.module_type', "Module"), mod[:title], $!) end @@ -92,7 +92,7 @@ def self.process_module(mod, migration) (mod['items'] || []).each do |item| next unless item['type'] == 'submodule' - self.process_module(item, migration) + process_module(item, migration) end end end @@ -101,7 +101,7 @@ def self.flatten_item(item, indent) if item['type'] == 'submodule' sub_items = [] sub_items << { :type => 'heading', :title => item['title'], :indent => indent, :migration_id => item['migration_id'] }.with_indifferent_access - sub_items += (item['items'] || []).map { |i| self.flatten_item(i, indent + 1) } + sub_items += (item['items'] || []).map { |i| flatten_item(i, indent + 1) } sub_items else item[:indent] = (item[:indent] || 0) + indent @@ -162,12 +162,12 @@ def self.import_from_migration(hash, context, migration, item = nil) item_map = {} item.item_migration_position ||= (item.content_tags.not_deleted.pluck(:position).compact + [item.content_tags.not_deleted.count]).max items = hash[:items] || [] - items = items.map { |i| self.flatten_item(i, 0) }.flatten + items = items.map { |i| flatten_item(i, 0) }.flatten imported_migration_ids = [] items.each do |tag_hash| - tags = self.add_module_item_from_migration(item, tag_hash, 0, context, item_map, migration) + tags = add_module_item_from_migration(item, tag_hash, 0, context, item_map, migration) imported_migration_ids.concat tags.map(&:migration_id) rescue migration.add_import_warning(t(:migration_module_item_type, "Module Item"), tag_hash[:title], $!) @@ -368,7 +368,7 @@ def self.add_module_item_from_migration(context_module, hash, level, context, it items << item end hash[:sub_items]&.each do |tag_hash| - items.concat self.add_module_item_from_migration(context_module, tag_hash, level + 1, context, item_map, migration) + items.concat add_module_item_from_migration(context_module, tag_hash, level + 1, context, item_map, migration) end items end diff --git a/app/models/importers/course_content_importer.rb b/app/models/importers/course_content_importer.rb index 8c9c72df20cfd..a4f3c057aaf67 100644 --- a/app/models/importers/course_content_importer.rb +++ b/app/models/importers/course_content_importer.rb @@ -113,7 +113,7 @@ def self.import_content(course, data, _params, migration) migration.update_import_progress(20) mo_attachments = migration.imported_migration_items_by_class(Attachment).find_all { |i| i.media_entry_id.present? } begin - self.import_media_objects(mo_attachments, migration) + import_media_objects(mo_attachments, migration) rescue => e er = Canvas::Errors.capture_exception(:import_media_objects, e)[:error_report] error_message = t('Failed to import media objects') @@ -180,7 +180,7 @@ def self.import_content(course, data, _params, migration) everything_selected = !migration.copy_options || migration.is_set?(migration.copy_options[:everything]) if everything_selected || migration.is_set?(migration.copy_options[:all_course_settings]) - self.import_settings_from_migration(course, data, migration) + import_settings_from_migration(course, data, migration) end migration.update_import_progress(90) @@ -200,7 +200,7 @@ def self.import_content(course, data, _params, migration) syllabus_should_be_added = everything_selected || migration.copy_options[:syllabus_body] || migration.copy_options[:all_syllabus_body] if syllabus_should_be_added syllabus_body = data[:course][:syllabus_body] if data[:course] - self.import_syllabus_from_migration(course, syllabus_body, migration) if syllabus_body + import_syllabus_from_migration(course, syllabus_body, migration) if syllabus_body end course.save! if course.changed? @@ -292,7 +292,7 @@ def self.move_to_assignment_group(course, migration) def self.adjust_dates(course, migration) # Adjust dates if (shift_options = migration.date_shift_options) - shift_options = self.shift_date_options(course, shift_options) + shift_options = shift_date_options(course, shift_options) Assignment.suspend_due_date_caching do migration.imported_migration_items_by_class(Assignment).each do |event| diff --git a/app/models/importers/discussion_topic_importer.rb b/app/models/importers/discussion_topic_importer.rb index fb5f890c913b0..63e0452da9842 100644 --- a/app/models/importers/discussion_topic_importer.rb +++ b/app/models/importers/discussion_topic_importer.rb @@ -37,7 +37,7 @@ def self.process_announcements_migration(announcements, migration) event[:type] = 'announcement' begin - self.import_from_migration(event, migration.context, migration) + import_from_migration(event, migration.context, migration) rescue migration.add_import_warning(t('#migration.announcement_type', "Announcement"), event[:title], $!) end @@ -67,7 +67,7 @@ def self.can_import_topic?(topic, migration) end def self.import_from_migration(hash, context, migration, item = nil) - importer = self.new(hash, context, migration, item) + importer = new(hash, context, migration, item) importer.run end diff --git a/app/models/importers/external_feed_importer.rb b/app/models/importers/external_feed_importer.rb index 0bc1eaa2c6afa..00954f204b8f2 100644 --- a/app/models/importers/external_feed_importer.rb +++ b/app/models/importers/external_feed_importer.rb @@ -29,7 +29,7 @@ def self.process_migration(data, migration) tools.each do |tool| if tool['migration_id'] && (!to_import || to_import[tool['migration_id']]) begin - self.import_from_migration(tool, migration.context, migration) + import_from_migration(tool, migration.context, migration) rescue migration.add_import_warning(t('#migration.external_feed_type', "External Feed"), tool[:title], $!) end diff --git a/app/models/importers/grading_standard_importer.rb b/app/models/importers/grading_standard_importer.rb index 1f8cfb29a16a1..75c2522a078a9 100644 --- a/app/models/importers/grading_standard_importer.rb +++ b/app/models/importers/grading_standard_importer.rb @@ -36,7 +36,7 @@ def self.process_migration(data, migration) standards.each do |standard| if migration.import_object?('grading_standards', standard['migration_id']) begin - self.import_from_migration(standard, migration.context, migration) + import_from_migration(standard, migration.context, migration) rescue migration.add_import_warning(t('#migration.grading_standard_type', "Grading Standard"), standard[:title], $!) end diff --git a/app/models/importers/group_importer.rb b/app/models/importers/group_importer.rb index 023a3865f8f31..12f555e3a2ca7 100644 --- a/app/models/importers/group_importer.rb +++ b/app/models/importers/group_importer.rb @@ -28,7 +28,7 @@ def self.process_migration(data, migration) groups.each do |group| if migration.import_object?("groups", group['migration_id']) begin - self.import_from_migration(group, migration.context, migration) + import_from_migration(group, migration.context, migration) rescue migration.add_import_warning(t('#migration.group_type', "Group"), group[:title], $!) end diff --git a/app/models/importers/pace_plan_importer.rb b/app/models/importers/pace_plan_importer.rb index a0b363e745b7c..10b7aa1280b16 100644 --- a/app/models/importers/pace_plan_importer.rb +++ b/app/models/importers/pace_plan_importer.rb @@ -26,7 +26,7 @@ class PacePlanImporter < Importer def self.process_migration(data, migration) pace_plans = data['pace_plans'] || [] pace_plans.each do |pace_plan| - self.import_from_migration(pace_plan, migration.context, migration) + import_from_migration(pace_plan, migration.context, migration) end end diff --git a/app/models/importers/quiz_importer.rb b/app/models/importers/quiz_importer.rb index 9a19872f8b9ea..55b8a20f8fabf 100644 --- a/app/models/importers/quiz_importer.rb +++ b/app/models/importers/quiz_importer.rb @@ -234,7 +234,7 @@ def self.import_from_migration(hash, context, migration, question_data = nil, it recache_due_dates = item.assignment&.needs_update_cached_due_dates # quiz ends up getting reloaded by the end build_assignment = false - self.import_questions(item, hash, context, migration, question_data, new_record) + import_questions(item, hash, context, migration, question_data, new_record) if hash[:assignment] if hash[:assignment][:migration_id] && !hash[:assignment][:migration_id].start_with?(MasterCourses::MIGRATION_ID_PREFIX) diff --git a/app/models/importers/quiz_question_importer.rb b/app/models/importers/quiz_question_importer.rb index ece56bba052dc..09f78314d4f5d 100644 --- a/app/models/importers/quiz_question_importer.rb +++ b/app/models/importers/quiz_question_importer.rb @@ -48,13 +48,13 @@ def self.import_from_migration(aq_hash, qq_hash, position, qq_ids, context, migr quiz&.id, quiz_group&.id, hash['assessment_question_id'], hash.to_yaml, Time.now.utc, Time.now.utc, mig_id, position, root_account_id ] - query = self.item_class.send(:sanitize_sql, [<<~SQL.squish, *args]) + query = item_class.send(:sanitize_sql, [<<~SQL.squish, *args]) INSERT INTO #{Quizzes::QuizQuestion.quoted_table_name} (quiz_id, quiz_group_id, assessment_question_id, question_data, created_at, updated_at, migration_id, position, root_account_id) VALUES (?,?,?,?,?,?,?,?,?) SQL GuardRail.activate(:primary) do - qq_ids[mig_id] = self.item_class.connection.insert(query, "#{self.item_class.name} Create", - self.item_class.primary_key, nil, self.item_class.sequence_name) + qq_ids[mig_id] = item_class.connection.insert(query, "#{item_class.name} Create", + item_class.primary_key, nil, item_class.sequence_name) end end hash diff --git a/app/models/importers/rubric_importer.rb b/app/models/importers/rubric_importer.rb index 5ec1d9c1060f8..c20a39ab4571a 100644 --- a/app/models/importers/rubric_importer.rb +++ b/app/models/importers/rubric_importer.rb @@ -30,7 +30,7 @@ def self.process_migration(data, migration) rubrics.each do |rubric| if migration.import_object?("rubrics", rubric['migration_id']) begin - self.import_from_migration(rubric, migration) + import_from_migration(rubric, migration) rescue migration.add_import_warning(t('#migration.rubric_type', "Rubric"), rubric[:title], $!) end diff --git a/app/models/importers/wiki_page_importer.rb b/app/models/importers/wiki_page_importer.rb index ffbd3c0b0b9d1..f420a3810215c 100644 --- a/app/models/importers/wiki_page_importer.rb +++ b/app/models/importers/wiki_page_importer.rb @@ -32,7 +32,7 @@ def self.process_migration_course_outline(data, migration) outline['root_folder'] = true begin - self.import_from_migration(outline.merge({ :outline_folders_to_import => to_import }), migration.context, migration) + import_from_migration(outline.merge({ :outline_folders_to_import => to_import }), migration.context, migration) rescue migration.add_warning("Error importing the course outline.", $!) end @@ -54,7 +54,7 @@ def self.process_migration(data, migration) next unless wiki_page_migration?(migration, wiki) begin - self.import_from_migration(wiki, migration.context, migration) if wiki + import_from_migration(wiki, migration.context, migration) if wiki rescue migration.add_import_warning(t('#migration.wiki_page_type', "Wiki Page"), wiki[:title], $!) end diff --git a/app/models/learning_outcome.rb b/app/models/learning_outcome.rb index 03412d516cbd2..5f3fd33ed78f0 100644 --- a/app/models/learning_outcome.rb +++ b/app/models/learning_outcome.rb @@ -55,27 +55,27 @@ class LearningOutcome < ActiveRecord::Base set_policy do # managing a contextual outcome requires manage_outcomes on the outcome's context - given { |user, session| self.context_id && self.context.grants_right?(user, session, :manage_outcomes) } + given { |user, session| context_id && context.grants_right?(user, session, :manage_outcomes) } can :create and can :read and can :update and can :delete # reading a contextual outcome is also allowed by read_outcomes on the outcome's context - given { |user, session| self.context_id && self.context.grants_right?(user, session, :read_outcomes) } + given { |user, session| context_id && context.grants_right?(user, session, :read_outcomes) } can :read # managing a global outcome requires manage_global_outcomes on the site_admin - given { |user, session| self.context_id.nil? && Account.site_admin.grants_right?(user, session, :manage_global_outcomes) } + given { |user, session| context_id.nil? && Account.site_admin.grants_right?(user, session, :manage_global_outcomes) } can :create and can :read and can :update and can :delete # reading a global outcome is also allowed by just being logged in - given { |user| self.context_id.nil? && user } + given { |user| context_id.nil? && user } can :read end def infer_defaults - if self.data && self.data[:rubric_criterion] - self.data[:rubric_criterion][:description] = self.short_description + if data && data[:rubric_criterion] + data[:rubric_criterion][:description] = short_description end - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" rescue nil + self.context_code = "#{context_type.underscore}_#{context_id}" rescue nil # if we are changing the calculation_method but not the calculation_int, set the int to the default value if calculation_method_changed? && !calculation_int_changed? @@ -84,12 +84,12 @@ def infer_defaults end def infer_root_account_ids - return if self.root_account_ids.present? + return if root_account_ids.present? context_root_account_id = context.try(:resolved_root_account_id) # find linked contexts - links = if self.new_record? + links = if new_record? [] else ContentTag.learning_outcome_links @@ -104,20 +104,20 @@ def infer_root_account_ids end def add_root_account_id_for_context!(context) - return if self.root_account_ids.nil? # not initialized yet + return if root_account_ids.nil? # not initialized yet root_account_id = context.try(:resolved_root_account_id) return if root_account_id.nil? - unless self.root_account_ids.include? root_account_id - self.root_account_ids << root_account_id - self.save! + unless root_account_ids.include? root_account_id + root_account_ids << root_account_id + save! end end def validate_calculation_int unless self.class.valid_calculation_int?(calculation_int, calculation_method) - valid_ints = self.class.valid_calculation_ints(self.calculation_method) + valid_ints = self.class.valid_calculation_ints(calculation_method) if valid_ints.to_a.empty? errors.add(:calculation_int, t( "A calculation value is not used with this calculation method" @@ -188,19 +188,19 @@ def align(asset, context, opts = {}) create_missing_outcome_link(context) if MasterCourses::MasterTemplate.is_master_course?(context) # mark for re-sync - context.learning_outcome_links.where(content: self).touch_all if self.context_type == "Account" - self.touch + context.learning_outcome_links.where(content: self).touch_all if context_type == "Account" + touch end end tag end def remove_alignment(alignment_id, context) - tag = self.alignments.where({ - context_id: context, - context_type: context.class_name, - id: alignment_id - }).first + tag = alignments.where({ + context_id: context, + context_type: context.class_name, + id: alignment_id + }).first tag&.destroy tag end @@ -227,7 +227,7 @@ def self.update_alignments(asset, context, new_outcome_ids) end def title - self.short_description + short_description end def title=(new_title) @@ -241,8 +241,8 @@ def title=(new_title) end def cached_context_short_name - @cached_context_name ||= Rails.cache.fetch(['short_name_lookup', self.context_code].cache_key) do - self.context.short_name rescue "" + @cached_context_name ||= Rails.cache.fetch(['short_name_lookup', context_code].cache_key) do + context.short_name rescue "" end end @@ -321,7 +321,7 @@ def destroy def assessed?(course = nil) if course - self.learning_outcome_results.active.where(context_id: course, context_type: "Course").exists? + learning_outcome_results.active.where(context_id: course, context_type: "Course").exists? else if learning_outcome_results.active.loaded? learning_outcome_results.active.any? @@ -336,11 +336,11 @@ def tie_to(context) end def mastery_points - self.rubric_criterion[:mastery_points] + rubric_criterion[:mastery_points] end def points_possible - self.rubric_criterion[:points_possible] + rubric_criterion[:points_possible] end def mastery_percent @@ -358,7 +358,7 @@ def artifacts_count_for_tied_context @tied_context.all_courses.select(:id).map(&:asset_string) end end - self.learning_outcome_results.active.for_context_codes(codes).count + learning_outcome_results.active.for_context_codes(codes).count end def self.delete_if_unused(ids) @@ -395,10 +395,10 @@ def self.ensure_presence_in_context(outcome_ids, context) def propagate_changes_to_rubrics # exclude new outcomes - return if self.saved_change_to_id? - return if !self.saved_change_to_data? && - !self.saved_change_to_short_description? && - !self.saved_change_to_description? + return if saved_change_to_id? + return if !saved_change_to_data? && + !saved_change_to_short_description? && + !saved_change_to_description? delay_if_production.update_associated_rubrics end @@ -414,7 +414,7 @@ def update_associated_rubrics end def updateable_rubrics - conds = { learning_outcome_id: self.id, content_type: 'Rubric', workflow_state: 'active' } + conds = { learning_outcome_id: id, content_type: 'Rubric', workflow_state: 'active' } # Find all unassessed, active rubrics aligned to this outcome, referenced by no more than one assignment Rubric.where( id: Rubric @@ -437,13 +437,13 @@ def create_missing_outcome_link(context) content_type: "LearningOutcome" ).pluck(:content_id) - unless context_outcomes.include?(self.id) + unless context_outcomes.include?(id) context.root_outcome_group.add_outcome(self) end end def find_or_create_tag(asset, context) - self.alignments.find_or_create_by( + alignments.find_or_create_by( content: asset, tag_type: 'learning_outcome', context: context diff --git a/app/models/learning_outcome_group.rb b/app/models/learning_outcome_group.rb index 6484c9020dedf..2ec51613ca36a 100644 --- a/app/models/learning_outcome_group.rb +++ b/app/models/learning_outcome_group.rb @@ -58,10 +58,10 @@ def parent_ids end def touch_parent_group - return if self.skip_parent_group_touch + return if skip_parent_group_touch - self.touch - self.learning_outcome_group&.touch_parent_group + touch + learning_outcome_group&.touch_parent_group end # adds a new link to an outcome to this group. does nothing if a link already @@ -76,7 +76,7 @@ def add_outcome(outcome, skip_touch: false, migration_id: nil) touch_parent_group child_outcome_links.create( content: outcome, - context: self.context || self, + context: context || self, skip_touch: skip_touch, migration_id: migration_id ) @@ -84,7 +84,7 @@ def add_outcome(outcome, skip_touch: false, migration_id: nil) def sync_source_group transaction do - return unless self.source_outcome_group + return unless source_outcome_group source_outcome_group.child_outcome_links.active.each do |link| add_outcome(link.content, skip_touch: true) @@ -104,7 +104,7 @@ def sync_source_group target_child_group.description = source_child_group.description target_child_group.vendor_guid = source_child_group.vendor_guid target_child_group.source_outcome_group = source_child_group - target_child_group.context = self.context + target_child_group.context = context target_child_group.skip_parent_group_touch = true target_child_group.save! end @@ -128,7 +128,7 @@ def add_outcome_group(original, opts = {}) copy.title = original.title copy.description = original.description copy.vendor_guid = original.vendor_guid - copy.context = self.context + copy.context = context copy.skip_parent_group_touch = true copy.save! @@ -146,7 +146,7 @@ def add_outcome_group(original, opts = {}) copy.add_outcome(link.content, skip_touch: true) end - self.context&.touch unless opts[:skip_touch] + context&.touch unless opts[:skip_touch] touch_parent_group # done @@ -157,14 +157,14 @@ def add_outcome_group(original, opts = {}) # moves an existing outcome link from the same context to be under this # group. def adopt_outcome_link(outcome_link, opts = {}) - return if self.context && self.context != outcome_link.context + return if context && context != outcome_link.context # no-op if the group is global and the link isn't - return if self.context.nil? && outcome_link.context_type != 'LearningOutcomeGroup' + return if context.nil? && outcome_link.context_type != 'LearningOutcomeGroup' # no-op if we're already the parent return outcome_link if outcome_link.associated_asset == self # update context_id if global - outcome_link.context_id = self.id if self.context.nil? + outcome_link.context_id = id if context.nil? # change the parent outcome_link.associated_asset = self @@ -177,14 +177,14 @@ def adopt_outcome_link(outcome_link, opts = {}) # group. cannot move an ancestor of the group. def adopt_outcome_group(group) # can only move within context, and no cycles! - return unless group.context == self.context + return unless group.context == context return if is_ancestor?(group.id) # no-op if we're already the parent return group if group.parent_outcome_group == self # change the parent - group.learning_outcome_group_id = self.id + group.learning_outcome_group_id = id group.save! group end @@ -195,11 +195,11 @@ def destroy transaction do # delete the children of the group, both links and subgroups, then delete # the group itself - self.child_outcome_links.active.preload(:content).each do |outcome_link| + child_outcome_links.active.preload(:content).each do |outcome_link| outcome_link.skip_touch = true if @skip_tag_touch outcome_link.destroy end - self.child_outcome_groups.active.each do |outcome_group| + child_outcome_groups.active.each do |outcome_group| outcome_group.skip_tag_touch = true if @skip_tag_touch outcome_group.destroy end @@ -255,7 +255,7 @@ def self.order_by_title # because of old broken behavior a group can have multiple parents, including itself def ancestor_ids unless @ancestor_ids - @ancestor_ids = [self.id] + @ancestor_ids = [id] ids_to_check = parent_ids - @ancestor_ids until ids_to_check.empty? @@ -263,7 +263,7 @@ def ancestor_ids new_ids = [] ids_to_check.each do |id| - group = LearningOutcomeGroup.for_context(self.context).active.where(id: id).first + group = LearningOutcomeGroup.for_context(context).active.where(id: id).first new_ids += group.parent_ids if group end @@ -277,7 +277,7 @@ def ancestor_ids private def infer_defaults - self.context ||= self.parent_outcome_group&.context + self.context ||= parent_outcome_group&.context if self.context&.learning_outcome_groups&.exists? && !building_default default = self.context.root_outcome_group self.learning_outcome_group_id ||= default.id unless self == default diff --git a/app/models/learning_outcome_question_result.rb b/app/models/learning_outcome_question_result.rb index 35c5510be3afd..c59afac4e6c1e 100644 --- a/app/models/learning_outcome_question_result.rb +++ b/app/models/learning_outcome_question_result.rb @@ -36,31 +36,31 @@ class LearningOutcomeQuestionResult < ActiveRecord::Base before_save :set_root_account_id def infer_defaults - self.original_score ||= self.score - self.original_possible ||= self.possible - self.original_mastery = self.mastery if self.original_mastery.nil? + self.original_score ||= score + self.original_possible ||= possible + self.original_mastery = mastery if original_mastery.nil? calculate_percent! true end def set_root_account_id - return if self.root_account_id.present? + return if root_account_id.present? - self.root_account_id = self.learning_outcome_result.root_account_id + self.root_account_id = learning_outcome_result.root_account_id end def calculate_percent! - if self.score && self.possible - self.percent = self.score.to_f / self.possible.to_f + if score && possible + self.percent = score.to_f / possible.to_f end - self.percent = nil if self.percent && !self.percent.to_f.finite? + self.percent = nil if percent && !percent.to_f.finite? end def save_to_version(attempt) - if self.versions.empty? + if versions.empty? save else - current_version = self.versions.current.model + current_version = versions.current.model if current_version.attempt && attempt < current_version.attempt versions = self.versions.sort_by(&:created_at).reverse.select { |v| v.model.attempt == attempt } unless versions.empty? @@ -78,11 +78,11 @@ def save_to_version(attempt) def update_version_data(version) version_data = YAML.load(version.yaml) - version_data["score"] = self.score - version_data["mastery"] = self.mastery - version_data["possible"] = self.possible - version_data["attempt"] = self.attempt - version_data["title"] = self.title + version_data["score"] = score + version_data["mastery"] = mastery + version_data["possible"] = possible + version_data["attempt"] = attempt + version_data["title"] = title version.yaml = version_data.to_yaml version.save end diff --git a/app/models/learning_outcome_result.rb b/app/models/learning_outcome_result.rb index 20963a90e3144..891d89df74038 100644 --- a/app/models/learning_outcome_result.rb +++ b/app/models/learning_outcome_result.rb @@ -48,26 +48,26 @@ class LearningOutcomeResult < ActiveRecord::Base def calculate_percent! scale_data = scale_params - if needs_scale?(scale_data) && self.score && self.possible + if needs_scale?(scale_data) && score && possible self.percent = calculate_by_scale(scale_data).round(4) - elsif self.score + elsif score self.percent = percentage end - self.percent = nil if self.percent && !self.percent.to_f.finite? + self.percent = nil if percent && !percent.to_f.finite? end def percentage - if self.possible.to_f > 0 - self.score.to_f / self.possible.to_f + if possible.to_f > 0 + score.to_f / possible.to_f elsif context&.root_account&.feature_enabled?(:account_level_mastery_scales) && outcome_proficiency.present? && outcome_proficiency.points_possible > 0 - self.score.to_f / outcome_proficiency.points_possible.to_f + score.to_f / outcome_proficiency.points_possible.to_f elsif parent_has_mastery? # the parent should always have a mastery score, if it doesn't # it means something is broken with the outcome and it will need to # be corrected. If percent is nil on an Outcome Result associated with # a Quiz, it will cause a 500 error on the learning mastery gradebook in # the get_aggregates method in RollupScoreAggregatorHelper - self.score.to_f / parent_outcome.mastery_points.to_f + score.to_f / parent_outcome.mastery_points.to_f end end @@ -77,12 +77,12 @@ def outcome_proficiency end def assignment - if self.association_object.is_a?(Assignment) - self.association_object - elsif self.artifact.is_a?(RubricAssessment) - self.artifact.rubric_association.association_object - elsif self.association_object.is_a? Quizzes::Quiz - self.association_object.assignment + if association_object.is_a?(Assignment) + association_object + elsif artifact.is_a?(RubricAssessment) + artifact.rubric_association.association_object + elsif association_object.is_a? Quizzes::Quiz + association_object.assignment else nil end @@ -90,17 +90,17 @@ def assignment def save_to_version(attempt) InstStatsd::Statsd.increment('learning_outcome_result.create') if new_record? - current_version = self.versions.current.try(:model) + current_version = versions.current.try(:model) if current_version.try(:attempt) && attempt < current_version.attempt versions = self.versions.sort_by(&:created_at).reverse.select { |v| v.model.attempt == attempt } if !versions.empty? versions.each do |version| version_data = YAML.load(version.yaml) - version_data["score"] = self.score - version_data["mastery"] = self.mastery - version_data["possible"] = self.possible + version_data["score"] = score + version_data["mastery"] = mastery + version_data["possible"] = possible version_data["attempt"] = self.attempt - version_data["title"] = self.title + version_data["title"] = title version.yaml = version_data.to_yaml version.save end @@ -158,43 +158,43 @@ def submitted_or_assessed_at private def infer_defaults - self.learning_outcome_id = self.alignment.learning_outcome_id - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" rescue nil - self.original_score ||= self.score - self.original_possible ||= self.possible - self.original_mastery = self.mastery if self.original_mastery.nil? + self.learning_outcome_id = alignment.learning_outcome_id + self.context_code = "#{context_type.underscore}_#{context_id}" rescue nil + self.original_score ||= score + self.original_possible ||= possible + self.original_mastery = mastery if original_mastery.nil? calculate_percent! true end def ensure_user_uuid - self.user_uuid = self.user&.uuid if self.user_uuid.blank? + self.user_uuid = user&.uuid if user_uuid.blank? end def set_root_account_id - return if self.root_account_id.present? + return if root_account_id.present? - self.root_account_id = self.context&.resolved_root_account_id + self.root_account_id = context&.resolved_root_account_id end def calculate_by_scale(scale_data) scale_percent = scale_data[:scale_percent] alignment_mastery = scale_data[:alignment_mastery] - scale_points = (self.possible / scale_percent) - self.possible - scale_cutoff = self.possible - (self.possible * alignment_mastery) - percent_to_scale = (self.score + scale_cutoff) - self.possible + scale_points = (possible / scale_percent) - possible + scale_cutoff = possible - (possible * alignment_mastery) + percent_to_scale = (score + scale_cutoff) - possible if percent_to_scale > 0 && scale_cutoff > 0 score_adjustment = (percent_to_scale / scale_cutoff) * scale_points - scaled_score = self.score + score_adjustment - (scaled_score / self.possible) * scale_percent + scaled_score = score + score_adjustment + (scaled_score / possible) * scale_percent else - (self.score / self.possible) * scale_percent + (score / possible) * scale_percent end end def scale_params parent_mastery = precise_mastery_percent - alignment_mastery = self.alignment.mastery_score + alignment_mastery = alignment.mastery_score return unless parent_mastery && alignment_mastery if parent_mastery > 0 && alignment_mastery > 0 @@ -208,7 +208,7 @@ def parent_has_mastery? end def parent_outcome - self.learning_outcome + learning_outcome end def needs_scale?(scale_data) diff --git a/app/models/live_assessments/assessment.rb b/app/models/live_assessments/assessment.rb index 14fe17331eba8..b49693f9d0c6b 100644 --- a/app/models/live_assessments/assessment.rb +++ b/app/models/live_assessments/assessment.rb @@ -34,24 +34,24 @@ class Assessment < ActiveRecord::Base set_policy do given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments) + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments) end can :create and can :update given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_add) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_add) end can :create given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_edit) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_edit) end can :update - given { |user, session| self.context.grants_right?(user, session, :view_all_grades) } + given { |user, session| context.grants_right?(user, session, :view_all_grades) } can :read end diff --git a/app/models/live_assessments/result.rb b/app/models/live_assessments/result.rb index b9f65360725ac..b73b431e5c8e2 100644 --- a/app/models/live_assessments/result.rb +++ b/app/models/live_assessments/result.rb @@ -30,10 +30,10 @@ class Result < ActiveRecord::Base scope :for_user, lambda { |user| where(:user_id => user) } set_policy do - given { |user, session| self.assessment.grants_right?(user, session, :update) } + given { |user, session| assessment.grants_right?(user, session, :update) } can :create - given { |user, session| self.assessment.grants_right?(user, session, :read) } + given { |user, session| assessment.grants_right?(user, session, :read) } can :read end end diff --git a/app/models/lti/line_item.rb b/app/models/lti/line_item.rb index aa0959a9afdff..ce36a2143e6d2 100644 --- a/app/models/lti/line_item.rb +++ b/app/models/lti/line_item.rb @@ -50,11 +50,11 @@ class Lti::LineItem < ApplicationRecord AGS_EXT_SUBMISSION_TYPE = 'https://canvas.instructure.com/lti/submission_type' def assignment_line_item? - assignment.line_items.order(:created_at).first.id == self.id + assignment.line_items.order(:created_at).first.id == id end def self.create_line_item!(assignment, context, tool, params) - self.transaction do + transaction do assignment_attr = { context: context, name: params[:label], @@ -84,7 +84,7 @@ def self.create_line_item!(assignment, context, tool, params) line_item = assignment.line_items.first end - line_item ||= self.new(assignment: assignment, root_account_id: assignment.root_account_id) + line_item ||= new(assignment: assignment, root_account_id: assignment.root_account_id) attrs = params.to_h.merge(coupled: false).compact attrs[:client_id] = tool.global_developer_key_id if tool line_item.update!(attrs) @@ -124,7 +124,7 @@ def client_id_is_global? # this is to prevent orphaned (ie undeleted state) line_items when an assignment is destroyed def destroy_resource_link - self.resource_link&.destroy + resource_link&.destroy end # This is to delete assignments that were created with the line items API @@ -132,7 +132,7 @@ def destroy_resource_link def destroy_assignment return unless assignment_line_item? && !coupled - self.assignment.destroy + assignment.destroy end def set_root_account_id diff --git a/app/models/lti/resource_link.rb b/app/models/lti/resource_link.rb index 543933cdf9721..1a956402e6dec 100644 --- a/app/models/lti/resource_link.rb +++ b/app/models/lti/resource_link.rb @@ -93,6 +93,6 @@ def generate_resource_link_uuid end def set_root_account - self.root_account_id ||= self.original_context_external_tool&.root_account_id + self.root_account_id ||= original_context_external_tool&.root_account_id end end diff --git a/app/models/lti/result.rb b/app/models/lti/result.rb index 8d410d059b843..7520290ba2b00 100644 --- a/app/models/lti/result.rb +++ b/app/models/lti/result.rb @@ -110,6 +110,6 @@ def self.update_score_for_submission(submission, score) private def set_root_account - self.root_account_id ||= self.submission&.root_account_id || self.line_item&.root_account_id + self.root_account_id ||= submission&.root_account_id || line_item&.root_account_id end end diff --git a/app/models/lti/tool_configuration.rb b/app/models/lti/tool_configuration.rb index 565af69fa154c..23ea7b168b13f 100644 --- a/app/models/lti/tool_configuration.rb +++ b/app/models/lti/tool_configuration.rb @@ -67,7 +67,7 @@ def self.create_tool_config_and_key!(account, tool_configuration_params) redirect_uris = settings[:target_link_uri] raise_error(:configuration, "Configuration must be present") if settings.blank? - self.transaction do + transaction do dk = DeveloperKey.create!( account: (account.site_admin? ? nil : account), is_lti_key: true, @@ -76,7 +76,7 @@ def self.create_tool_config_and_key!(account, tool_configuration_params) redirect_uris: redirect_uris || [], scopes: settings[:scopes] || [] ) - self.create!( + create!( developer_key: dk, configuration: settings.deep_merge( 'custom_fields' => ContextExternalTool.find_custom_fields_from_string(tool_configuration_params[:custom_fields]) @@ -102,7 +102,7 @@ def self.retrieve_and_extract_configuration(url) private_class_method :retrieve_and_extract_configuration def self.raise_error(type, message) - tool_config_obj = self.new + tool_config_obj = new tool_config_obj.errors.add(type, message) raise ActiveRecord::RecordInvalid, tool_config_obj end diff --git a/app/models/lti/tool_proxy.rb b/app/models/lti/tool_proxy.rb index b9c9bf8c955c9..2141d61c43873 100644 --- a/app/models/lti/tool_proxy.rb +++ b/app/models/lti/tool_proxy.rb @@ -86,17 +86,17 @@ def self.proxies_in_order_by_codes(context:, vendor_code:, product_code:, resour OR (lti_tool_proxy_bindings.context_type = ? AND lti_tool_proxy_bindings.context_id IN (?))', context.class.name, context.id, 'Account', account_ids) .order("lti_tool_proxy_bindings.tool_proxy_id, x.ordering").to_sql - tools = self.joins("JOIN (#{subquery}) bindings on lti_tool_proxies.id = bindings.tool_proxy_id") - .select('lti_tool_proxies.*, bindings.enabled AS binding_enabled'). + tools = joins("JOIN (#{subquery}) bindings on lti_tool_proxies.id = bindings.tool_proxy_id") + .select('lti_tool_proxies.*, bindings.enabled AS binding_enabled'). # changed this from eager_load, because eager_load likes to wipe out custom select attributes joins(:product_family) - .joins(:resources). + .joins(:resources). # changed the order to go from the special ordering set up (to make sure we're going from the course to the # root account in order of parent accounts) and then takes the most recently installed tool order('ordering, lti_tool_proxies.id DESC') - .where(lti_tool_proxies: { workflow_state: 'active' }) - .where('lti_product_families.vendor_code = ? AND lti_product_families.product_code = ?', vendor_code, product_code) - .where(lti_resource_handlers: { resource_type_code: resource_type_code }) + .where(lti_tool_proxies: { workflow_state: 'active' }) + .where('lti_product_families.vendor_code = ? AND lti_product_families.product_code = ?', vendor_code, product_code) + .where(lti_resource_handlers: { resource_type_code: resource_type_code }) # You can disable a tool_binding somewhere in the account chain, and anything below that that reenables it should be # available, but nothing above it, so we're getting rid of anything that is disabled and above tools.split { |tool| !tool.binding_enabled }.first @@ -125,7 +125,7 @@ def default_resource_handler end def update? - self.update_payload.present? + update_payload.present? end def ims_tool_proxy @@ -185,9 +185,9 @@ def manage_subscription # new subscriptions will get all events for the whole root account, and are # filtered by the associatedIntegrationId (tool guid) inside the live events # publish tool. - if self.subscription_id.blank? && workflow_state == 'active' && plagiarism_tool? + if subscription_id.blank? && workflow_state == 'active' && plagiarism_tool? subscription_id = Lti::PlagiarismSubscriptionsHelper.new(self)&.create_subscription - self.update_columns(subscription_id: subscription_id) + update_columns(subscription_id: subscription_id) elsif self.subscription_id.present? && workflow_state != 'active' delete_subscription end @@ -197,7 +197,7 @@ def delete_subscription return if subscription_id.nil? Lti::PlagiarismSubscriptionsHelper.new(self).destroy_subscription(subscription_id) - self.update_columns(subscription_id: nil) + update_columns(subscription_id: nil) end def plagiarism_tool? diff --git a/app/models/many_root_accounts.rb b/app/models/many_root_accounts.rb index 7204fb3aa71ac..a9cf5881cc515 100644 --- a/app/models/many_root_accounts.rb +++ b/app/models/many_root_accounts.rb @@ -21,7 +21,7 @@ module ManyRootAccounts def global_root_account_ids root_account_ids&.map do |id| - Shard.global_id_for(id, self.shard) + Shard.global_id_for(id, shard) end end end diff --git a/app/models/master_courses/child_content_tag.rb b/app/models/master_courses/child_content_tag.rb index 116a116d48946..3689a7679bfe4 100644 --- a/app/models/master_courses/child_content_tag.rb +++ b/app/models/master_courses/child_content_tag.rb @@ -55,6 +55,6 @@ def set_migration_id end def set_root_account_id - self.root_account_id ||= self.child_subscription.root_account_id + self.root_account_id ||= child_subscription.root_account_id end end diff --git a/app/models/master_courses/child_subscription.rb b/app/models/master_courses/child_subscription.rb index 6d1c94a609e89..8ff1e2910caf4 100644 --- a/app/models/master_courses/child_subscription.rb +++ b/app/models/master_courses/child_subscription.rb @@ -35,8 +35,8 @@ class MasterCourses::ChildSubscription < ActiveRecord::Base def require_same_root_account # at some point we may want to expand this so it can be done across trusted root accounts # but for now make sure they're in the same root account so we don't have to worry about cross-shard course copies yet - if self.child_course.root_account_id != self.master_template.course.root_account_id - self.errors.add(:child_course_id, t("Child course must belong to the same root account as master course")) + if child_course.root_account_id != master_template.course.root_account_id + errors.add(:child_course_id, t("Child course must belong to the same root account as master course")) end end @@ -51,8 +51,8 @@ def require_same_root_account self.content_tag_association = :child_content_tags def invalidate_course_cache - if self.saved_change_to_workflow_state? - Rails.cache.delete(self.class.course_cache_key(self.child_course)) + if saved_change_to_workflow_state? + Rails.cache.delete(self.class.course_cache_key(child_course)) end end @@ -63,7 +63,7 @@ def self.course_cache_key(course_id) def self.is_child_course?(course_id) Rails.cache.fetch(course_cache_key(course_id)) do course_id = course_id.id if course_id.is_a?(Course) - self.where(:child_course_id => course_id).active.exists? + where(:child_course_id => course_id).active.exists? end end @@ -72,14 +72,14 @@ def check_migration_id_deactivation if workflow_state_changed? if deleted? && workflow_state_was == 'active' self.class.connection.after_transaction_commit do - self.unlink_syllabus! - self.add_deactivation_prefix! + unlink_syllabus! + add_deactivation_prefix! end elsif active? && workflow_state_was == 'deleted' self.use_selective_copy = false # require a full import next time self.class.connection.after_transaction_commit do - self.link_syllabus! - self.remove_deactivation_prefix! + link_syllabus! + remove_deactivation_prefix! end end end @@ -87,34 +87,34 @@ def check_migration_id_deactivation def deactivation_prefix # a silly string to prepend onto all the bc object migration ids when we deactivate - "deletedsub_#{self.id}_" + "deletedsub_#{id}_" end def link_syllabus! - self.child_course.syllabus_master_template_id = self.master_template_id - self.child_course.save! + child_course.syllabus_master_template_id = master_template_id + child_course.save! end def unlink_syllabus! - self.child_course.syllabus_master_template_id = nil - self.child_course.save! + child_course.syllabus_master_template_id = nil + child_course.save! end def add_deactivation_prefix! - where_clause = ["migration_id IS NOT NULL AND migration_id LIKE ?", "#{MasterCourses::MasterTemplate.migration_id_prefix(self.shard.id, self.master_template_id)}%"] - update_query = ["migration_id = concat(?, migration_id)", self.deactivation_prefix] + where_clause = ["migration_id IS NOT NULL AND migration_id LIKE ?", "#{MasterCourses::MasterTemplate.migration_id_prefix(shard.id, master_template_id)}%"] + update_query = ["migration_id = concat(?, migration_id)", deactivation_prefix] update_content_in_child_course(where_clause, update_query) end def remove_deactivation_prefix! where_clause = ["migration_id LIKE ?", "#{deactivation_prefix}%"] - update_query = ["migration_id = substr(migration_id, ?)", self.deactivation_prefix.length + 1] + update_query = ["migration_id = substr(migration_id, ?)", deactivation_prefix.length + 1] update_content_in_child_course(where_clause, update_query) end def update_content_in_child_course(where_clause, update_query) - if self.child_content_tags.where(where_clause).update_all(update_query) > 0 # don't run all the rest of it if there's no reason to - self.content_scopes_for_deactivation.each do |scope| + if child_content_tags.where(where_clause).update_all(update_query) > 0 # don't run all the rest of it if there's no reason to + content_scopes_for_deactivation.each do |scope| scope.where(where_clause).find_ids_in_batches do |ids| scope.where(where_clause).where(scope.klass.primary_key => ids).update_all(update_query) end @@ -124,7 +124,7 @@ def update_content_in_child_course(where_clause, update_query) def content_scopes_for_deactivation # there are more things we've added the restrictor module to, but we may not bother actually restricting them in the end - c = self.child_course + c = child_course [ c.assignments, c.attachments, @@ -140,6 +140,6 @@ def last_migration_id end def set_root_account_id - self.root_account_id = self.child_course.root_account_id + self.root_account_id = child_course.root_account_id end end diff --git a/app/models/master_courses/collection_restrictor.rb b/app/models/master_courses/collection_restrictor.rb index 7275e8c3e31d9..c7fe4b08d4d57 100644 --- a/app/models/master_courses/collection_restrictor.rb +++ b/app/models/master_courses/collection_restrictor.rb @@ -36,28 +36,28 @@ def self.included(klass) module ClassMethods def restrict_columns(edit_type, columns) - raise "set the collection owner first" unless self.collection_owner_association + raise "set the collection owner first" unless collection_owner_association super - owner_class = self.reflections[self.collection_owner_association.to_s].klass + owner_class = reflections[collection_owner_association.to_s].klass owner_class.restrict_columns(edit_type, pseudocolumn_for_type(edit_type)) # e.g. add "assessment_questions_content" as a restricted column end def pseudocolumn_for_type(type) # prepend with table name because it looks better than "Quizzes::QuizQuestion" - "#{self.table_name}_#{type}" + "#{table_name}_#{type}" end end def check_restrictions? - if self.is_a?(Quizzes::QuizQuestion) - !self.generated? # allow updating through the bank even though it's technically locked... shhh don't tell anybody + if is_a?(Quizzes::QuizQuestion) + !generated? # allow updating through the bank even though it's technically locked... shhh don't tell anybody else true end end def owner_for_restrictions - self.send(self.class.base_class.collection_owner_association) + send(self.class.base_class.collection_owner_association) end # delegate to the owner @@ -65,9 +65,7 @@ def is_child_content? owner_for_restrictions&.is_child_content? end - def child_content_restrictions - self.owner_for_restrictions.child_content_restrictions - end + delegate :child_content_restrictions, to: :owner_for_restrictions def mark_downstream_changes return if @importing_migration || !is_child_content? # don't mark changes on import @@ -75,10 +73,10 @@ def mark_downstream_changes # instead of marking the exact columns - i'm just going to be lazy and mark the edit type on the owner, e.g. "quiz_questions_content" changed_types = [] self.class.base_class.restricted_column_settings.each do |edit_type, columns| - if (self.saved_changes.keys & columns).any? + if (saved_changes.keys & columns).any? changed_types << self.class.pseudocolumn_for_type(edit_type) # pretend it's sort of like a column in the downstream changes end end - self.owner_for_restrictions.mark_downstream_changes(changed_types) if changed_types.any? # store changes on owner + owner_for_restrictions.mark_downstream_changes(changed_types) if changed_types.any? # store changes on owner end end diff --git a/app/models/master_courses/master_content_tag.rb b/app/models/master_courses/master_content_tag.rb index 2fd644dbcdaa1..f26c2e35cfdf8 100644 --- a/app/models/master_courses/master_content_tag.rb +++ b/app/models/master_courses/master_content_tag.rb @@ -51,55 +51,55 @@ class MasterCourses::MasterContentTag < ActiveRecord::Base after_save :touch_content_if_restrictions_tightened def set_migration_id - self.migration_id = self.master_template.migration_id_for(self.content) + self.migration_id = master_template.migration_id_for(content) end def set_root_account_id - self.root_account_id = self.master_template.root_account_id + self.root_account_id = master_template.root_account_id end def require_valid_restrictions # this may be changed in the future - if self.restrictions_changed? && (self.restrictions.keys != [:all]) - if (self.restrictions.keys - MasterCourses::LOCK_TYPES).any? - self.errors.add(:restrictions, "Invalid settings") + if restrictions_changed? && (restrictions.keys != [:all]) + if (restrictions.keys - MasterCourses::LOCK_TYPES).any? + errors.add(:restrictions, "Invalid settings") end end end def mark_touch_content_if_restrictions_tightened - if !self.new_record? && self.restrictions_changed? && self.restrictions.any? { |type, locked| locked && !self.restrictions_was[type] } + if !new_record? && restrictions_changed? && restrictions.any? { |type, locked| locked && !restrictions_was[type] } @touch_content = true # set if restrictions for content or settings is true now when it wasn't before so we'll re-export and overwrite any changed content end end def touch_content_if_restrictions_tightened if @touch_content - self.content.touch + content.touch @touch_content = false end end def self.fetch_module_item_restrictions_for_child(item_ids) # does a silly fancy doublejoin so we can get all the restrictions in one query - data = self - .joins("INNER JOIN #{MasterCourses::ChildContentTag.quoted_table_name} ON - #{self.table_name}.migration_id=#{MasterCourses::ChildContentTag.table_name}.migration_id") - .joins("INNER JOIN #{ContentTag.quoted_table_name} ON + data = + joins("INNER JOIN #{MasterCourses::ChildContentTag.quoted_table_name} ON + #{table_name}.migration_id=#{MasterCourses::ChildContentTag.table_name}.migration_id") + .joins("INNER JOIN #{ContentTag.quoted_table_name} ON #{MasterCourses::ChildContentTag.table_name}.content_type=#{ContentTag.table_name}.content_type AND #{MasterCourses::ChildContentTag.table_name}.content_id=#{ContentTag.table_name}.content_id") - .where(:content_tags => { :id => item_ids }) - .pluck('content_tags.id', :restrictions) + .where(:content_tags => { :id => item_ids }) + .pluck('content_tags.id', :restrictions) data.to_h end def self.fetch_module_item_restrictions_for_master(item_ids) - data = self - .joins("INNER JOIN #{ContentTag.quoted_table_name} ON - #{self.table_name}.content_type=#{ContentTag.table_name}.content_type AND - #{self.table_name}.content_id=#{ContentTag.table_name}.content_id") - .where(:content_tags => { :id => item_ids }) - .pluck('content_tags.id', :restrictions) + data = + joins("INNER JOIN #{ContentTag.quoted_table_name} ON + #{table_name}.content_type=#{ContentTag.table_name}.content_type AND + #{table_name}.content_id=#{ContentTag.table_name}.content_id") + .where(:content_tags => { :id => item_ids }) + .pluck('content_tags.id', :restrictions) hash = data.to_h (item_ids - hash.keys).each do |missing_id| # populate blank restrictions for all items without mastercontenttags created yet hash[missing_id] = {} diff --git a/app/models/master_courses/master_migration.rb b/app/models/master_courses/master_migration.rb index 1065e5b55c101..f8091fe5ec141 100644 --- a/app/models/master_courses/master_migration.rb +++ b/app/models/master_courses/master_migration.rb @@ -85,11 +85,11 @@ def self.start_new_migration!(master_template, user, opts = {}) end def copy_settings=(val) - self.migration_settings[:copy_settings] = val + migration_settings[:copy_settings] = val end def publish_after_initial_sync=(val) - self.migration_settings[:publish_after_initial_sync] = val + migration_settings[:publish_after_initial_sync] = val end def hours_until_expire @@ -97,56 +97,56 @@ def hours_until_expire end def in_running_state? - %w[created queued exporting imports_queued].include?(self.workflow_state) + %w[created queued exporting imports_queued].include?(workflow_state) end def still_running? # if something catastrophic happens, just give up after 24 hours - in_running_state? && self.created_at > self.hours_until_expire.hours.ago + in_running_state? && created_at > hours_until_expire.hours.ago end def expire_if_necessary! - if in_running_state? && self.created_at < self.hours_until_expire.hours.ago - self.workflow_state = (self.workflow_state == 'imports_queued') ? 'imports_failed' : 'exports_failed' - self.save! + if in_running_state? && created_at < hours_until_expire.hours.ago + self.workflow_state = (workflow_state == 'imports_queued') ? 'imports_failed' : 'exports_failed' + save! end end def queue_export_job - expires_at = self.hours_until_expire.hours.from_now + expires_at = hours_until_expire.hours.from_now queue_opts = { :priority => Delayed::LOW_PRIORITY, :max_attempts => 1, :expires_at => expires_at, :on_permanent_failure => :fail_export_with_error!, - :n_strand => ["master_course_exports", self.master_template.course.global_root_account_id] + :n_strand => ["master_course_exports", master_template.course.global_root_account_id] # we may need to raise the n_strand limit (in the settings) for this key since it'll default to 1 at a time } - self.update_attribute(:workflow_state, 'queued') + update_attribute(:workflow_state, 'queued') delay(**queue_opts).perform_exports end def fail_export_with_error!(exception_or_info) if exception_or_info.is_a?(Exception) report_id = Canvas::Errors.capture_exception(:master_course_migration, exception_or_info)[:error_report] - self.export_results[:error_report_id] = report_id + export_results[:error_report_id] = report_id else - self.export_results[:error_message] = exception_or_info + export_results[:error_message] = exception_or_info end self.workflow_state = 'exports_failed' - self.save + save end def perform_exports self.workflow_state = 'exporting' self.exports_started_at = Time.now - self.save! + save! - subs = self.master_template.child_subscriptions.active.preload(:child_course).to_a + subs = master_template.child_subscriptions.active.preload(:child_course).to_a subs.reject! { |s| s.child_course.deleted? } if subs.empty? self.workflow_state = 'completed' - self.export_results[:message] = "No child courses to export to" - self.save! + export_results[:message] = "No child courses to export to" + save! return end @@ -161,37 +161,37 @@ def perform_exports cms += export_to_child_courses(:selective, up_to_date_subs, true).to_a if up_to_date_subs.any? cms += export_to_child_courses(:full, new_subs, up_to_date_subs.none?).to_a if new_subs.any? - unless self.workflow_state == 'exports_failed' + unless workflow_state == 'exports_failed' self.workflow_state = 'imports_queued' self.imports_queued_at = Time.now - self.save! - self.queue_imports(cms) + save! + queue_imports(cms) end rescue => e - self.fail_export_with_error!(e) + fail_export_with_error!(e) raise e end def export_to_child_courses(type, subscriptions, export_is_primary) @export_type = type if type == :selective - @deletions = self.master_template.deletions_since_last_export + @deletions = master_template.deletions_since_last_export @creations = {} # will be populated during export @updates = {} # " @export_count = 0 end - export = self.create_export(type, export_is_primary, :deletions => @deletions) + export = create_export(type, export_is_primary, :deletions => @deletions) if export.exported_for_course_copy? - self.export_results[type] = { :subscriptions => subscriptions.map(&:id), :content_export_id => export.id } + export_results[type] = { :subscriptions => subscriptions.map(&:id), :content_export_id => export.id } if type == :selective - self.export_results[type][:deleted] = @deletions - self.export_results[type][:created] = @creations - self.export_results[type][:updated] = @updates + export_results[type][:deleted] = @deletions + export_results[type][:created] = @creations + export_results[type][:updated] = @updates end - self.generate_imports(type, export, subscriptions) + generate_imports(type, export, subscriptions) else - self.fail_export_with_error!("#{type} content export #{export.id} failed") + fail_export_with_error!("#{type} content export #{export.id} failed") nil end end @@ -201,13 +201,13 @@ def create_export(type, is_primary, export_opts) # in CC::Importer::Canvas to turn it into the big ol' "course_export.json" and we'll save that alone # and return it ce = ContentExport.new - ce.context = self.master_template.course + ce.context = master_template.course ce.export_type = ContentExport::MASTER_COURSE_COPY ce.settings[:master_migration_type] = type - ce.settings[:master_migration_id] = self.id # so we can find on the import side when we copy attachments + ce.settings[:master_migration_id] = id # so we can find on the import side when we copy attachments ce.settings[:primary_master_migration] = is_primary ce.settings[:selected_content] = selected_content(type) - ce.user = self.user + ce.user = user ce.save! ce.master_migration = self # don't need to reload ce.export_course(export_opts) @@ -234,7 +234,7 @@ def selected_content(type) end def last_export_at - self.master_template.last_export_started_at + master_template.last_export_started_at end def export_object?(obj) @@ -242,7 +242,7 @@ def export_object?(obj) return true if last_export_at.nil? if obj.is_a?(LearningOutcome) && obj.context_type == "Account" - link = self.master_template.course.learning_outcome_links.where(content: obj).first + link = master_template.course.learning_outcome_links.where(content: obj).first obj = link if link # export the outcome if it's a new link end obj.updated_at.nil? || obj.updated_at >= last_export_at @@ -250,7 +250,7 @@ def export_object?(obj) def detect_updated_attachments(type) # because attachments don't get "added" to the export - scope = self.master_template.course.attachments.not_deleted + scope = master_template.course.attachments.not_deleted scope = scope.where('updated_at>?', last_export_at) if type == :selective && last_export_at scope.each do |att| master_template.ensure_tag_on_export(att) @@ -289,50 +289,50 @@ def generate_imports(type, export, subscriptions) cm.migration_settings[:skip_import_notification] = true cm.migration_settings[:hide_from_index] = true # we may decide we want to show this after all, but hide them for now cm.migration_settings[:master_course_export_id] = export.id - cm.migration_settings[:master_migration_id] = self.id - cm.migration_settings[:publish_after_completion] = type == :full && self.migration_settings[:publish_after_initial_sync] + cm.migration_settings[:master_migration_id] = id + cm.migration_settings[:publish_after_completion] = type == :full && migration_settings[:publish_after_initial_sync] cm.child_subscription_id = sub.id - cm.source_course_id = self.master_template.course_id # apparently this is how some lti tools try to track copied content :/ + cm.source_course_id = master_template.course_id # apparently this is how some lti tools try to track copied content :/ cm.workflow_state = 'exported' cm.exported_attachment = export.attachment cm.user_id = export.user_id cm.save! - self.migration_results.create!(:content_migration => cm, :import_type => type, :child_subscription_id => sub.id, :state => "queued") + migration_results.create!(:content_migration => cm, :import_type => type, :child_subscription_id => sub.id, :state => "queued") cms << cm end - self.save! + save! cms end def queue_imports(cms) - imports_expire_at = self.created_at + hours_until_expire.hours # tighten the limit until the import jobs expire + imports_expire_at = created_at + hours_until_expire.hours # tighten the limit until the import jobs expire cms.each { |cm| cm.queue_migration(MigrationPluginStub, expires_at: imports_expire_at) } # this job is finished now but we won't mark ourselves as "completed" until all the import migrations are finished end def update_import_state!(import_migration, state) - res = self.migration_results.where(:content_migration_id => import_migration).first + res = migration_results.where(:content_migration_id => import_migration).first res.state = state res.results[:skipped] = import_migration.skipped_master_course_items.to_a if import_migration.skipped_master_course_items res.save! if state == 'completed' && res.import_type == 'full' - if (sub = self.master_template.child_subscriptions.active.where(:id => res.child_subscription_id, :use_selective_copy => false).first) + if (sub = master_template.child_subscriptions.active.where(:id => res.child_subscription_id, :use_selective_copy => false).first) sub.update_attribute(:use_selective_copy, true) # mark subscription as up-to-date end end - unless self.migration_results.where.not(:state => %w[completed failed]).exists? + unless migration_results.where.not(:state => %w[completed failed]).exists? self.class.transaction do - self.lock! - if self.workflow_state == 'imports_queued' - if self.migration_results.where.not(:state => "completed").exists? + lock! + if workflow_state == 'imports_queued' + if migration_results.where.not(:state => "completed").exists? self.workflow_state = 'imports_failed' else self.workflow_state = 'completed' self.imports_completed_at = Time.now end - self.save! + save! end end end @@ -351,6 +351,6 @@ def notification_link_anchor end def set_root_account_id - self.root_account_id = self.master_template.root_account_id + self.root_account_id = master_template.root_account_id end end diff --git a/app/models/master_courses/master_template.rb b/app/models/master_courses/master_template.rb index e66d39afa11f6..a7c4143799eb3 100644 --- a/app/models/master_courses/master_template.rb +++ b/app/models/master_courses/master_template.rb @@ -61,80 +61,80 @@ class MasterCourses::MasterTemplate < ActiveRecord::Base after_destroy :destroy_subscriptions_later def set_defaults - unless self.default_restrictions.present? + unless default_restrictions.present? self.default_restrictions = { :content => true } end end def set_root_account_id - self.root_account_id = self.course.root_account_id + self.root_account_id = course.root_account_id end def invalidate_course_cache - if self.saved_change_to_workflow_state? - Rails.cache.delete(self.class.course_cache_key(self.course)) + if saved_change_to_workflow_state? + Rails.cache.delete(self.class.course_cache_key(course)) end end def sync_default_restrictions - if self.use_default_restrictions_by_type - if self.saved_change_to_use_default_restrictions_by_type? || self.saved_change_to_default_restrictions_by_type? + if use_default_restrictions_by_type + if saved_change_to_use_default_restrictions_by_type? || saved_change_to_default_restrictions_by_type? MasterCourses::RESTRICTED_OBJECT_TYPES.each do |type| - new_type_restrictions = self.default_restrictions_by_type[type] || {} - count = self.master_content_tags.where(:use_default_restrictions => true, :content_type => type) - .update_all(:restrictions => new_type_restrictions) + new_type_restrictions = default_restrictions_by_type[type] || {} + count = master_content_tags.where(:use_default_restrictions => true, :content_type => type) + .update_all(:restrictions => new_type_restrictions) next unless count > 0 - old_type_restrictions = self.default_restrictions_by_type_before_last_save[type] || {} + old_type_restrictions = default_restrictions_by_type_before_last_save[type] || {} if new_type_restrictions.any? { |setting, locked| locked && !old_type_restrictions[setting] } # tightened restrictions - self.touch_all_content_for_tags(type) + touch_all_content_for_tags(type) end end end else - if self.saved_change_to_default_restrictions? - count = self.master_content_tags.where(:use_default_restrictions => true) - .update_all(:restrictions => self.default_restrictions) - if count > 0 && self.default_restrictions.any? { |setting, locked| locked && !self.default_restrictions_before_last_save[setting] } # tightened restrictions - self.touch_all_content_for_tags + if saved_change_to_default_restrictions? + count = master_content_tags.where(:use_default_restrictions => true) + .update_all(:restrictions => default_restrictions) + if count > 0 && default_restrictions.any? { |setting, locked| locked && !default_restrictions_before_last_save[setting] } # tightened restrictions + touch_all_content_for_tags end end end end def destroy_subscriptions_later - delay_if_production(n_strand: ["master_courses_destroy_subscriptions", self.course.global_root_account_id], + delay_if_production(n_strand: ["master_courses_destroy_subscriptions", course.global_root_account_id], priority: Delayed::LOW_PRIORITY).destroy_subscriptions end def destroy_subscriptions - self.child_subscriptions.active.each(&:destroy) + child_subscriptions.active.each(&:destroy) end def touch_all_content_for_tags(only_content_type = nil) content_types = if only_content_type [only_content_type] else - self.master_content_tags.where(:use_default_restrictions => true).distinct.pluck(:content_type) + master_content_tags.where(:use_default_restrictions => true).distinct.pluck(:content_type) end content_types.each do |content_type| klass = content_type.constantize - klass.where(klass.primary_key => self.master_content_tags.where(:use_default_restrictions => true, - :content_type => content_type).select(:content_id)).touch_all + klass.where(klass.primary_key => master_content_tags.where(:use_default_restrictions => true, + :content_type => content_type).select(:content_id)).touch_all end end def require_valid_restrictions - if self.default_restrictions_changed? - if (self.default_restrictions.keys - MasterCourses::LOCK_TYPES).any? - self.errors.add(:default_restrictions, "Invalid settings") + if default_restrictions_changed? + if (default_restrictions.keys - MasterCourses::LOCK_TYPES).any? + errors.add(:default_restrictions, "Invalid settings") end end - if self.default_restrictions_by_type_changed? - if (self.default_restrictions_by_type.keys - MasterCourses::RESTRICTED_OBJECT_TYPES).any? - self.errors.add(:default_restrictions_by_type, "Invalid content type") - elsif self.default_restrictions_by_type.values.any? { |k, _v| (k.keys - MasterCourses::LOCK_TYPES).any? } - self.errors.add(:default_restrictions_by_type, "Invalid settings") + if default_restrictions_by_type_changed? + if (default_restrictions_by_type.keys - MasterCourses::RESTRICTED_OBJECT_TYPES).any? + errors.add(:default_restrictions_by_type, "Invalid content type") + elsif default_restrictions_by_type.values.any? { |k, _v| (k.keys - MasterCourses::LOCK_TYPES).any? } + errors.add(:default_restrictions_by_type, "Invalid settings") end end end @@ -146,7 +146,7 @@ def self.course_cache_key(course_id) def self.preload_is_master_course(courses) return if courses.length == 1 # not worth preloading for 1; let the cache be used - has_mc_courses = self.where(course: courses).active.distinct.pluck(:course_id).to_set + has_mc_courses = where(course: courses).active.distinct.pluck(:course_id).to_set courses.each do |course| course.is_master_course = has_mc_courses.include?(course.id) end @@ -159,12 +159,12 @@ def self.is_master_course?(course_id) Rails.cache.fetch(course_cache_key(course_id)) do course_id = course_id.id if course_id.is_a?(Course) - self.where(:course_id => course_id).active.exists? + where(:course_id => course_id).active.exists? end end def self.set_as_master_course(course) - self.unique_constraint_retry do + unique_constraint_retry do template = course.master_course_templates.for_full_course.first_or_create template.undestroy unless template.active? template @@ -172,7 +172,7 @@ def self.set_as_master_course(course) end def self.remove_as_master_course(course) - self.unique_constraint_retry do + unique_constraint_retry do template = course.master_course_templates.active.for_full_course.first template.destroy && template if template.present? end @@ -184,7 +184,7 @@ def self.full_template_for(course) def self.master_course_for_child_course(course_id) course_id = course_id.id if course_id.is_a?(Course) - mt_table = self.table_name + mt_table = table_name cs_table = MasterCourses::ChildSubscription.table_name Course.joins("INNER JOIN #{MasterCourses::MasterTemplate.quoted_table_name} ON #{mt_table}.course_id=courses.id AND #{mt_table}.workflow_state='active'") .joins("INNER JOIN #{MasterCourses::ChildSubscription.quoted_table_name} ON #{cs_table}.master_template_id=#{mt_table}.id AND #{cs_table}.workflow_state='active'") @@ -212,41 +212,41 @@ def migration_id_for(obj, prepend = "") obj = submittable # i.e. use the same migration id as the topic on a graded topic's assignment - same restrictions end key = obj.is_a?(ActiveRecord::Base) ? obj.global_asset_string : obj.to_s - "#{self.class.migration_id_prefix(self.shard.id, self.id)}#{Digest::MD5.hexdigest(prepend + key)}" + "#{self.class.migration_id_prefix(shard.id, id)}#{Digest::MD5.hexdigest(prepend + key)}" end def add_child_course!(child_course_or_id) MasterCourses::ChildSubscription.unique_constraint_retry do - child_sub = self.child_subscriptions.where(:child_course_id => child_course_or_id).first_or_create! + child_sub = child_subscriptions.where(:child_course_id => child_course_or_id).first_or_create! child_sub.undestroy if child_sub.deleted? child_sub end end def child_course_scope - self.shard.activate do - Course.shard(self.shard).not_deleted.where(:id => self.child_subscriptions.active.select(:child_course_id)) + shard.activate do + Course.shard(shard).not_deleted.where(:id => child_subscriptions.active.select(:child_course_id)) end end def associated_course_count - self.child_subscriptions.active.count + child_subscriptions.active.count end def active_migration_running? - self.active_migration&.still_running? + active_migration&.still_running? end def last_export_started_at unless defined?(@last_export_started_at) - @last_export_started_at = self.master_migrations.where(:workflow_state => "completed").order("id DESC").limit(1).pluck(:exports_started_at).first + @last_export_started_at = master_migrations.where(:workflow_state => "completed").order("id DESC").limit(1).pluck(:exports_started_at).first end @last_export_started_at end def last_export_completed_at unless defined?(@last_export_completed_at) - @last_export_completed_at = self.master_migrations.where(:workflow_state => "completed").order("id DESC").limit(1).pluck(:imports_completed_at).first + @last_export_completed_at = master_migrations.where(:workflow_state => "completed").order("id DESC").limit(1).pluck(:imports_completed_at).first end @last_export_completed_at end @@ -260,7 +260,7 @@ def ensure_tag_on_export(obj) def preload_restrictions! @preloaded_restrictions ||= begin index = {} - self.master_content_tags.pluck(:migration_id, :restrictions).each do |mig_id, restrictions| + master_content_tags.pluck(:migration_id, :restrictions).each do |mig_id, restrictions| index[mig_id] = restrictions end index @@ -290,13 +290,13 @@ def deletions_since_last_export end def default_restrictions_for(object) - if self.use_default_restrictions_by_type + if use_default_restrictions_by_type if object.is_a?(Assignment) && (submittable = object.submittable_object) object = submittable end - self.default_restrictions_by_type[object.class.base_class.name] || {} + default_restrictions_by_type[object.class.base_class.name] || {} else - self.default_restrictions + default_restrictions end end @@ -306,9 +306,9 @@ def default_restrictions_by_type_for_api def self.create_associations_from_sis(root_account, associations, messages, migrating_user = nil) associations.keys.each_slice(50) do |master_sis_ids| - templates = self.active.for_full_course.joins(:course) - .where(:courses => { :root_account_id => root_account, :sis_source_id => master_sis_ids }) - .select("#{self.table_name}.*, courses.sis_source_id AS sis_source_id, courses.account_id AS account_id").to_a + templates = active.for_full_course.joins(:course) + .where(:courses => { :root_account_id => root_account, :sis_source_id => master_sis_ids }) + .select("#{table_name}.*, courses.sis_source_id AS sis_source_id, courses.account_id AS account_id").to_a if templates.count != master_sis_ids.count (master_sis_ids - templates.map(&:sis_source_id)).each do |missing_id| associations[missing_id].each do |target_course_id| diff --git a/app/models/master_courses/migration_result.rb b/app/models/master_courses/migration_result.rb index f22533ac42358..5e85ff7a6f1b4 100644 --- a/app/models/master_courses/migration_result.rb +++ b/app/models/master_courses/migration_result.rb @@ -33,6 +33,6 @@ def skipped_items end def set_root_account_id - self.root_account_id ||= self.master_migration.root_account_id + self.root_account_id ||= master_migration.root_account_id end end diff --git a/app/models/master_courses/restrictor.rb b/app/models/master_courses/restrictor.rb index 6d56fe580b983..d0a48a8240d54 100644 --- a/app/models/master_courses/restrictor.rb +++ b/app/models/master_courses/restrictor.rb @@ -63,8 +63,8 @@ def restrict_columns(edit_type, columns) raise "invalid restriction type" unless MasterCourses::LOCK_TYPES.include?(edit_type) columns = Array(columns).map(&:to_s) - current = self.restricted_column_settings[edit_type] || [] - self.restricted_column_settings[edit_type] = (current + columns).uniq + current = restricted_column_settings[edit_type] || [] + restricted_column_settings[edit_type] = (current + columns).uniq end def restrict_assignment_columns @@ -86,24 +86,24 @@ def skip_downstream_changes! end def check_for_restricted_column_changes - return true if @importing_migration || !is_child_content? || !self.check_restrictions? + return true if @importing_migration || !is_child_content? || !check_restrictions? locked_columns = [] self.class.base_class.restricted_column_settings.each do |type, columns| - changed_columns = (self.changes.keys & columns) + changed_columns = (changes.keys & columns) if changed_columns.any? - locked_columns += changed_columns if self.child_content_restrictions[type] + locked_columns += changed_columns if child_content_restrictions[type] end end if locked_columns.any? - self.errors.add(:base, "cannot change column(s): #{locked_columns.join(", ")} - locked by Master Course") + errors.add(:base, "cannot change column(s): #{locked_columns.join(", ")} - locked by Master Course") end end def editing_restricted?(edit_type = :all) # edit_type can be :all, :any, or a specific type: :content, :settings, :due_dates, :availability_dates, :points return false unless is_child_content? - restrictions = self.child_content_restrictions + restrictions = child_content_restrictions return false unless restrictions.present? return true if restrictions[:all] @@ -121,20 +121,20 @@ def editing_restricted?(edit_type = :all) # edit_type can be :all, :any, or a sp end def check_restrictions? - !self.new_record? + !new_record? end def mark_downstream_changes(changed_columns = nil) return if @importing_migration || @skip_downstream_changes || !is_child_content? # don't mark changes on import - changed_columns ||= self.saved_changes.keys & self.class.base_class.restricted_column_settings.values.flatten - state_column = self.is_a?(Attachment) ? "file_state" : "workflow_state" - if self.saved_changes[state_column]&.last == "deleted" + changed_columns ||= saved_changes.keys & self.class.base_class.restricted_column_settings.values.flatten + state_column = is_a?(Attachment) ? "file_state" : "workflow_state" + if saved_changes[state_column]&.last == "deleted" changed_columns.delete(state_column) changed_columns << "manually_deleted" end if changed_columns.any? - tag_content = if self.is_a?(Assignment) && (submittable = self.submittable_object) + tag_content = if is_a?(Assignment) && (submittable = submittable_object) submittable # mark on the owner's tag else self @@ -148,7 +148,7 @@ def mark_downstream_changes(changed_columns = nil) child_tag.save! end else - Rails.logger.warn("Child content tag was not found for #{self.class.name} #{self.id} - either this is from old code or something bad happened") + Rails.logger.warn("Child content tag was not found for #{self.class.name} #{id} - either this is from old code or something bad happened") end end end @@ -171,19 +171,19 @@ def check_before_overwriting_child_content_on_import self.class.base_class.restricted_column_settings.each do |type, columns| changed_columns = (child_tag.downstream_changes & columns) # should unlink all changes if _any_ in the category has been changed if changed_columns.any? - if self.child_content_restrictions[type] # don't overwrite downstream changes _unless_ it's locked + if child_content_restrictions[type] # don't overwrite downstream changes _unless_ it's locked child_tag.downstream_changes -= changed_columns # remove them from the downstream changes since we overwrote child_tag.save! else # if not locked then we should undo _all_ the changes in the category (content or settings) we were about to make - columns_to_restore += (self.changes.keys & columns) + columns_to_restore += (changes.keys & columns) end end end - state_column = self.is_a?(Attachment) ? "file_state" : "workflow_state" - if self.changes[state_column]&.first == "deleted" && child_tag.downstream_changes.include?("manually_deleted") - if self.editing_restricted?(:any) + state_column = is_a?(Attachment) ? "file_state" : "workflow_state" + if changes[state_column]&.first == "deleted" && child_tag.downstream_changes.include?("manually_deleted") + if editing_restricted?(:any) child_tag.downstream_changes.delete("manually_deleted") child_tag.save! else @@ -193,8 +193,8 @@ def check_before_overwriting_child_content_on_import if columns_to_restore.any? @importing_migration.add_skipped_item(child_tag) - Rails.logger.debug("Undoing imported changes to #{self.class} #{self.id} because changed downstream - #{columns_to_restore.join(', ')}") - self.restore_attributes(columns_to_restore) + Rails.logger.debug("Undoing imported changes to #{self.class} #{id} because changed downstream - #{columns_to_restore.join(', ')}") + restore_attributes(columns_to_restore) end end @@ -210,7 +210,7 @@ def edit_types_locked_for_overwrite_on_import locked_types = [] self.class.base_class.restricted_column_settings.each do |type, columns| - if !self.child_content_restrictions[type] && (child_tag.downstream_changes & columns).any? + if !child_content_restrictions[type] && (child_tag.downstream_changes & columns).any? locked_types << type end end @@ -219,7 +219,7 @@ def edit_types_locked_for_overwrite_on_import end def is_child_content? - self.migration_id&.start_with?(MasterCourses::MIGRATION_ID_PREFIX) + migration_id&.start_with?(MasterCourses::MIGRATION_ID_PREFIX) end def child_content_restrictions @@ -228,25 +228,25 @@ def child_content_restrictions def master_course_api_restriction_data(course_status) hash = {} - if course_status == :child && self.is_child_content? + if course_status == :child && is_child_content? hash['is_master_course_child_content'] = true - is_restricted = self.editing_restricted?(:any) + is_restricted = editing_restricted?(:any) hash['restricted_by_master_course'] = is_restricted - hash['master_course_restrictions'] = self.child_content_restrictions if is_restricted - elsif course_status == :master && self.current_master_template_restrictions + hash['master_course_restrictions'] = child_content_restrictions if is_restricted + elsif course_status == :master && current_master_template_restrictions hash['is_master_course_master_content'] = true - is_restricted = self.current_master_template_restrictions.values.any? { |v| v } + is_restricted = current_master_template_restrictions.values.any? { |v| v } hash['restricted_by_master_course'] = is_restricted - hash['master_course_restrictions'] = self.current_master_template_restrictions if is_restricted + hash['master_course_restrictions'] = current_master_template_restrictions if is_restricted end hash end def find_child_content_restrictions if @importing_migration - @importing_migration.master_course_subscription.master_template.find_preloaded_restriction(self.migration_id) # for extra speeds on import + @importing_migration.master_course_subscription.master_template.find_preloaded_restriction(migration_id) # for extra speeds on import else - MasterCourses::MasterContentTag.where(:migration_id => self.migration_id).pluck(:restrictions).first + MasterCourses::MasterContentTag.where(:migration_id => migration_id).pluck(:restrictions).first end end diff --git a/app/models/master_courses/tag_helper.rb b/app/models/master_courses/tag_helper.rb index cc56f3b961441..ea87777629d9c 100644 --- a/app/models/master_courses/tag_helper.rb +++ b/app/models/master_courses/tag_helper.rb @@ -24,14 +24,14 @@ def self.included(klass) end def content_tags - self.send(self.content_tag_association) + send(content_tag_association) end def load_tags!(objects = nil) return if @content_tag_index && !objects # if we already loaded everything don't worry @content_tag_index ||= {} - tag_scope = self.content_tags + tag_scope = content_tags if objects return unless objects.any? @@ -62,7 +62,7 @@ def content_tag_for(content, defaults = {}) end tag else - self.content_tags.where(content: content).first || create_content_tag_for!(content, defaults) + content_tags.where(content: content).first || create_content_tag_for!(content, defaults) end end @@ -71,8 +71,8 @@ def create_content_tag_for!(content, defaults = {}) self.class.unique_constraint_retry do |retry_count| tag = nil - tag = self.content_tags.where(content: content).first if retry_count > 0 - tag ||= self.content_tags.create!(defaults.merge(:content => content)) + tag = content_tags.where(content: content).first if retry_count > 0 + tag ||= content_tags.create!(defaults.merge(:content => content)) tag end end diff --git a/app/models/media_object.rb b/app/models/media_object.rb index 890d0e6e50151..9800cc4079496 100644 --- a/app/models/media_object.rb +++ b/app/models/media_object.rb @@ -57,7 +57,7 @@ def self.find_by(**kwargs) end set_policy do - given { |user| (self.user && self.user == user) || self.context&.grants_right?(user, :manage_content) } + given { |user| (self.user && self.user == user) || context&.grants_right?(user, :manage_content) } can :add_captions and can :delete_captions end @@ -170,10 +170,10 @@ def self.create_if_id_exists(media_id, **create_opts) def update_title_on_kaltura client = CanvasKaltura::ClientV3.new client.startSession(CanvasKaltura::SessionType::ADMIN) - res = client.mediaUpdate(self.media_id, :name => self.user_entered_title) + res = client.mediaUpdate(media_id, :name => user_entered_title) unless res[:error] - self.title = self.user_entered_title - self.save + self.title = user_entered_title + save end res end @@ -183,58 +183,58 @@ def retrieve_details_later end def media_sources - CanvasKaltura::ClientV3.new.media_sources(self.media_id) + CanvasKaltura::ClientV3.new.media_sources(media_id) end def retrieve_details_ensure_codecs(attempt = 0) retrieve_details - if !transcoded_details && self.created_at > 6.hours.ago + if !transcoded_details && created_at > 6.hours.ago if attempt < 10 delay(run_at: (5 * attempt).minutes.from_now).retrieve_details_ensure_codecs(attempt + 1) else Canvas::Errors.capture(:media_object_failure, { message: "Kaltura flavor retrieval failed", - object: self.inspect.to_s, + object: inspect.to_s, }, :warn) end end end def name - self.title + title end def guaranteed_title - self.user_entered_title.presence || self.title.presence || I18n.t("Untitled") + user_entered_title.presence || title.presence || I18n.t("Untitled") end def process_retrieved_details(entry, media_type, assets) if entry - self.title = self.title.presence || entry[:name] + self.title = title.presence || entry[:name] self.media_type = media_type self.duration = entry[:duration].to_i - self.data[:plays] = entry[:plays].to_i - self.data[:download_url] = entry[:downloadUrl] + data[:plays] = entry[:plays].to_i + data[:download_url] = entry[:downloadUrl] tags = (entry[:tags] || "").split(",").map(&:strip) old_id = tags.detect { |t| t.include?('old_id_') } self.old_media_id = old_id.sub(/old_id_/, '') if old_id end - self.data[:extensions] ||= {} + data[:extensions] ||= {} assets.each do |asset| asset[:fileExt] = "none" if asset[:fileExt].blank? - self.data[:extensions][asset[:fileExt].to_sym] = asset # .slice(:width, :height, :id, :entryId, :status, :containerFormat, :fileExt, :size + data[:extensions][asset[:fileExt].to_sym] = asset # .slice(:width, :height, :id, :entryId, :status, :containerFormat, :fileExt, :size if asset[:size] - self.max_size = [self.max_size || 0, asset[:size].to_i].max + self.max_size = [max_size || 0, asset[:size].to_i].max end end - self.total_size = [self.max_size || 0, assets.sum { |a| (a[:size] || 0).to_i }].max - self.save + self.total_size = [max_size || 0, assets.sum { |a| (a[:size] || 0).to_i }].max + save ensure_attachment - self.data + data end def retrieve_details - return unless self.media_id + return unless media_id # From Kaltura, retrieve the title (if it's not already set) # and the list of valid flavors along with their id's. @@ -243,18 +243,18 @@ def retrieve_details client.startSession(CanvasKaltura::SessionType::ADMIN) self.data ||= {} - entry = client.mediaGet(self.media_id) + entry = client.mediaGet(media_id) media_type = client.mediaTypeToSymbol(entry[:mediaType]).to_s if entry # attachment#build_content_types_sql assumes the content_type has a "/" media_type = "#{media_type}/*" unless media_type.blank? || media_type.include?("/") - assets = client.flavorAssetGetByEntryId(self.media_id) || [] + assets = client.flavorAssetGetByEntryId(media_id) || [] process_retrieved_details(entry, media_type, assets) end def podcast_format_details data = transcoded_details unless data - self.retrieve_details + retrieve_details data = transcoded_details end data @@ -267,22 +267,22 @@ def transcoded_details end def delete_from_remote - return unless self.media_id + return unless media_id client = CanvasKaltura::ClientV3.new client.startSession(CanvasKaltura::SessionType::ADMIN) - client.mediaDelete(self.media_id) + client.mediaDelete(media_id) end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.attachment&.destroy + attachment&.destroy save! end def data - self.read_or_initialize_attribute(:data, {}) + read_or_initialize_attribute(:data, {}) end def viewed! @@ -292,7 +292,7 @@ def viewed! def updated_viewed_at_and_retrieve_details(time) self.data[:last_viewed_at] = [time, self.data[:last_viewed_at]].compact.max - self.retrieve_details + retrieve_details end def destroy_without_destroying_attachment @@ -302,18 +302,18 @@ def destroy_without_destroying_attachment end def ensure_attachment - return if self.attachment_id - return unless %w[Account Course Group User].include?(self.context_type) + return if attachment_id + return unless %w[Account Course Group User].include?(context_type) - sources = self.media_sources + sources = media_sources return unless sources.present? attachment = build_attachment({ "context" => context, - "display_name" => self.title, - "filename" => self.title, - "content_type" => self.media_type, - "media_entry_id" => self.media_id, + "display_name" => title, + "filename" => title, + "content_type" => media_type, + "media_entry_id" => media_id, "workflow_state" => "processed", "folder_id" => Folder.media_folder(context).id }) @@ -328,7 +328,7 @@ def ensure_attachment end def deleted? - self.workflow_state == 'deleted' + workflow_state == 'deleted' end scope :active, -> { where("media_objects.workflow_state<>'deleted'") } diff --git a/app/models/media_track.rb b/app/models/media_track.rb index 49b3b5b7b25b3..c26e985ccbf1d 100644 --- a/app/models/media_track.rb +++ b/app/models/media_track.rb @@ -33,12 +33,12 @@ class MediaTrack < ActiveRecord::Base } def webvtt_content - self.read_attribute(:webvtt_content) || self.content + read_attribute(:webvtt_content) || content end def convert_srt_to_wvtt - if self.content.exclude?('WEBVTT') && (self.content_changed? || self.read_attribute(:webvtt_content).nil?) - srt_content = self.content.dup + if content.exclude?('WEBVTT') && (content_changed? || read_attribute(:webvtt_content).nil?) + srt_content = content.dup srt_content.gsub!(/(:|^)(\d)(,|:)/, '\10\2\3') srt_content.gsub!(/([0-9]{2}:[0-9]{2}:[0-9]{2})(,)([0-9]{3})/, '\1.\3') srt_content.gsub!("\r\n", "\n") diff --git a/app/models/message.rb b/app/models/message.rb index bffa9e1343dd2..6abf225592578 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -68,7 +68,7 @@ def message end def for_queue - Queued.new(self.id, self.created_at) + Queued.new(id, created_at) end # Associations @@ -102,9 +102,9 @@ def for_queue validates :reply_to_name, length: { maximum: maximum_string_length }, allow_blank: true def prevent_updates - unless self.new_record? + unless new_record? # e.g. Message.where(:id => self.id, :created_at => self.created_at).update_all(...) - self.errors.add(:base, "Regular saving on messages is disabled - use save_using_update_all") + errors.add(:base, "Regular saving on messages is disabled - use save_using_update_all") end end @@ -121,8 +121,8 @@ def prevent_updates workflow do state :created do event :stage, :transitions_to => :staged do - self.dispatch_at = Time.now.utc + self.delay_for - if self.to != 'dashboard' + self.dispatch_at = Time.now.utc + delay_for + if to != 'dashboard' MessageDispatcher.dispatch(self) end end @@ -156,8 +156,8 @@ def prevent_updates event :close, :transitions_to => :closed event :bounce, :transitions_to => :bounced do # Permenant reminder that this bounced. - self.communication_channel.bounce_count += 1 - self.communication_channel.save! + communication_channel.bounce_count += 1 + communication_channel.save! self.is_bounced = true end event :recycle, :transitions_to => :staged @@ -190,15 +190,15 @@ def prevent_updates # turns out we can override this method inside the workflow gem to get a custom save for workflow transitions def persist_workflow_state(new_state) self.workflow_state = new_state - self.save_using_update_all + save_using_update_all end def save_using_update_all - self.shard.activate do + shard.activate do self.updated_at = Time.now.utc - updates = self.changes_to_save.transform_values(&:last) - self.class.in_partition(attributes).where(:id => self.id, :created_at => self.created_at).update_all(updates) - self.clear_changes_information + updates = changes_to_save.transform_values(&:last) + self.class.in_partition(attributes).where(:id => id, :created_at => created_at).update_all(updates) + clear_changes_information end end @@ -330,26 +330,26 @@ def default_url_options def sns_json @sns_json ||= begin custom_data = { - html_url: self.url, - user_id: self.user.global_id + html_url: url, + user_id: user.global_id } custom_data[:api_url] = content(:api_url) if content(:api_url) # no templates define this right now { - default: self.subject, + default: subject, GCM: { data: { - alert: self.subject, + alert: subject, }.merge(custom_data) }.to_json, APNS_SANDBOX: { aps: { - alert: self.subject + alert: subject } }.merge(custom_data).to_json, APNS: { aps: { - alert: self.subject + alert: subject } }.merge(custom_data).to_json }.to_json @@ -371,11 +371,11 @@ def html_to_simple_html(html, *opts) end def transpose_url_ids(html) - url_helper = Api::Html::UrlProxy.new(self, self.context, - HostUrl.context_host(self.link_root_account), + url_helper = Api::Html::UrlProxy.new(self, context, + HostUrl.context_host(link_root_account), HostUrl.protocol, - target_shard: self.link_root_account.shard) - Api::Html::Content.rewrite_outgoing(html, self.link_root_account, url_helper) + target_shard: link_root_account.shard) + Api::Html::Content.rewrite_outgoing(html, link_root_account, url_helper) end # infer a root account associated with the context that the user can log in to @@ -451,7 +451,7 @@ def notification_display_category def stage_without_dispatch! return if state == :bounced - self.dispatch_at = Time.now.utc + self.delay_for + self.dispatch_at = Time.now.utc + delay_for self.workflow_state = 'staged' end @@ -532,7 +532,7 @@ def get_template(filename) unless (File.exist?(path) rescue false) return false if filename.include?('slack') - filename = self.notification.name.downcase.gsub(/\s/, '_') + ".email.erb" + filename = notification.name.downcase.gsub(/\s/, '_') + ".email.erb" path = Canvas::MessageHelper.find_message_path(filename) end @@ -551,7 +551,7 @@ def get_template(filename) # # Returns file name for erb template def template_filename(path_type = nil) - self.notification.name.parameterize.underscore + "." + path_type + ".erb" + notification.name.parameterize.underscore + "." + path_type + ".erb" end # Public: Apply an HTML email template to this message. @@ -601,9 +601,9 @@ def populate_body(message_body_template, path_type, binding, filename) # currently, _email_footer.email.erb only contains a way for users to change notification prefs # they can only change it if they are registered in the first place # do not show this for emails telling users to register - if footer_message.present? && !self.notification&.registration? + if footer_message.present? && !notification&.registration? self.body = <<~TEXT.strip_heredoc - #{self.body} + #{body} @@ -616,7 +616,7 @@ def populate_body(message_body_template, path_type, binding, filename) end end - self.body + body end # Public: Prepare a message for delivery by setting body, subject, etc. @@ -625,18 +625,18 @@ def populate_body(message_body_template, path_type, binding, filename) # # Returns nothing. def parse!(path_type = nil, root_account: nil) - raise StandardError, "Cannot parse without a context" unless self.context + raise StandardError, "Cannot parse without a context" unless context # set @root_account using our pre_loaded_account, because link_root_account # is called many times. link_root_account(pre_loaded_account: root_account) # Get the users timezone but maintain the original timezone in order to set it back at the end original_time_zone = Time.zone.name || "UTC" - user_time_zone = self.user.try(:time_zone) || root_account_time_zone || original_time_zone + user_time_zone = user.try(:time_zone) || root_account_time_zone || original_time_zone Time.zone = user_time_zone # (temporarily) override course name with user's nickname for the course - hacked_course = apply_course_nickname_to_asset(self.context, self.user) + hacked_course = apply_course_nickname_to_asset(context, user) path_type ||= communication_channel.try(:path_type) || 'email' @@ -666,7 +666,7 @@ def parse!(path_type = nil, root_account: nil) end end - self.body + body ensure # Set the timezone back to what it originally was Time.zone = original_time_zone if original_time_zone.present? @@ -707,7 +707,7 @@ def deliver short_stat: 'message.deliver', tags: { path_type: path_type, notification_name: notification_name }) - global_account_id = Shard.global_id_for(root_account_id, self.shard) + global_account_id = Shard.global_id_for(root_account_id, shard) InstStatsd::Statsd.increment("message.deliver.#{path_type}.#{global_account_id}", short_stat: 'message.deliver_per_account', tags: { path_type: path_type, root_account_id: global_account_id }) @@ -728,7 +728,7 @@ def skip_and_cancel InstStatsd::Statsd.increment("message.skip.#{path_type}.#{notification_name}", short_stat: 'message.skip', tags: { path_type: path_type, notification_name: notification_name }) - self.cancel + cancel end # Public: Enqueues a message to the notification_service's sqs queue @@ -743,7 +743,7 @@ def enqueue_to_sqs tags: { path_type: path_type }) self.transmission_errors = "No notification targets specified" - self.set_transmission_error + set_transmission_error else targets.each do |target| Services::NotificationService.process( @@ -751,7 +751,7 @@ def enqueue_to_sqs notification_message, path_type, target, - self.notification&.priority? + notification&.priority? ) end complete_dispatch @@ -765,7 +765,7 @@ def enqueue_to_sqs ) error_string = "Exception: #{e.class}: #{e.message}\n\t#{e.backtrace.join("\n\t")}" self.transmission_errors = error_string - self.errored_dispatch + errored_dispatch raise end @@ -779,7 +779,7 @@ def notification_message when "push" sns_json when "twitter" - url = self.main_link || self.url + url = main_link || self.url message_length = MAX_TWITTER_MESSAGE_LENGTH - url.length - 1 truncated_body = HtmlTextHelper.strip_and_truncate(body, max_length: message_length) "#{truncated_body} #{url}" @@ -798,7 +798,7 @@ def notification_message def notification_targets case path_type when "push" - self.user.notification_endpoints.pluck(:arn) + user.notification_endpoints.pluck(:arn) when "twitter" twitter_service = user.user_services.where(service: 'twitter').first [ @@ -896,7 +896,7 @@ def media_context end def notification_service_id - "#{self.global_id}+#{self.created_at.to_i}" + "#{global_id}+#{created_at.to_i}" end def self.parse_notification_service_id(service_id) @@ -977,8 +977,8 @@ def move_messages_for_deleted_users # Returns nothing. def truncate_invalid_message [:body, :html_body].each do |attr| - if self.send(attr) && self.send(attr).bytesize > self.class.maximum_text_length - self.send("#{attr}=", Message.unavailable_message) + if send(attr) && send(attr).bytesize > self.class.maximum_text_length + send("#{attr}=", Message.unavailable_message) end end end @@ -1021,7 +1021,7 @@ def infer_feature_account # Raises Timeout::Error if the remote server times out. def deliver_via_email res = nil - logger.info "Delivering mail: #{self.inspect}" + logger.info "Delivering mail: #{inspect}" begin res = Mailer.create_message(self).deliver_now rescue Net::SMTPServerBusy => e @@ -1046,7 +1046,7 @@ def deliver_via_email ) end - self.errored_dispatch + errored_dispatch if raise_error raise @exception else @@ -1112,7 +1112,7 @@ def deliver_via_sms # # Returns nothing. def deliver_via_push - self.user.notification_endpoints.each do |notification_endpoint| + user.notification_endpoints.each do |notification_endpoint| notification_endpoint.destroy unless notification_endpoint.push_json(sns_json) end complete_dispatch @@ -1156,7 +1156,7 @@ def can_use_name_for_from?(c) def name_helper @name_helper ||= Messages::NameHelper.new( asset: context, - message_recipient: self.user, + message_recipient: user, notification_name: notification_name ) end diff --git a/app/models/microsoft_sync/group.rb b/app/models/microsoft_sync/group.rb index 4787022472dc8..f9230739900ef 100644 --- a/app/models/microsoft_sync/group.rb +++ b/app/models/microsoft_sync/group.rb @@ -87,7 +87,7 @@ def destroy end def restore! - return unless self.deleted? + return unless deleted? update!( workflow_state: 'pending', diff --git a/app/models/microsoft_sync/user_mapping.rb b/app/models/microsoft_sync/user_mapping.rb index 65a8159e7b895..7607262b4b259 100644 --- a/app/models/microsoft_sync/user_mapping.rb +++ b/app/models/microsoft_sync/user_mapping.rb @@ -143,11 +143,11 @@ def self.delete_old_user_mappings_later(account, batch_size = 1000) Rails.logger.info("Triggering Microsoft Sync User Mappings hard delete for account #{account.global_id}") # We only need one job deleting UserMappings, so we can drop all other jobs # for the same root account that try to start up. - self.delay_if_production(singleton: "microsoft_sync_delete_old_user_mappings_account_#{account.global_id}") - .delete_user_mappings_for_account(account, batch_size) + delay_if_production(singleton: "microsoft_sync_delete_old_user_mappings_account_#{account.global_id}") + .delete_user_mappings_for_account(account, batch_size) end def self.delete_user_mappings_for_account(account, batch_size) - while self.where(root_account: account).limit(batch_size).delete_all > 0; end + while where(root_account: account).limit(batch_size).delete_all > 0; end end end diff --git a/app/models/moderated_grading/provisional_grade.rb b/app/models/moderated_grading/provisional_grade.rb index b5e4549a3c965..d81414dbc39ea 100644 --- a/app/models/moderated_grading/provisional_grade.rb +++ b/app/models/moderated_grading/provisional_grade.rb @@ -83,9 +83,9 @@ def valid?(*) end def grade_attributes - self.as_json(:only => ModeratedGrading::GRADE_ATTRIBUTES_ONLY, - :methods => [:provisional_grade_id, :grade_matches_current_submission, :entered_score, :entered_grade], - :include_root => false) + as_json(:only => ModeratedGrading::GRADE_ATTRIBUTES_ONLY, + :methods => [:provisional_grade_id, :grade_matches_current_submission, :entered_score, :entered_grade], + :include_root => false) end def entered_score @@ -97,24 +97,22 @@ def entered_grade end def grade_matches_current_submission - submission.submitted_at.nil? || self.graded_at.nil? || submission.submitted_at <= self.graded_at + submission.submitted_at.nil? || graded_at.nil? || submission.submitted_at <= graded_at end def provisional_grade_id - self.id + id end def submission_comments if submission.all_submission_comments.loaded? submission.all_submission_comments.select { |c| c.provisional_grade_id == id || c.provisional_grade_id.nil? } else - submission.all_submission_comments.where("provisional_grade_id = ? OR provisional_grade_id IS NULL", self.id) + submission.all_submission_comments.where("provisional_grade_id = ? OR provisional_grade_id IS NULL", id) end end - def student - self.submission.student - end + delegate :student, to: :submission def publish!(skip_grade_calc: false) original_skip_grade_calc = submission.skip_grade_calc @@ -172,7 +170,7 @@ def publish_submission_comments! end def copy_submission_comments!(dest_provisional_grade) - self.submission_comments.each do |prov_comment| + submission_comments.each do |prov_comment| pub_comment = prov_comment.dup pub_comment.provisional_grade_id = dest_provisional_grade && dest_provisional_grade.id pub_comment.save! @@ -180,7 +178,7 @@ def copy_submission_comments!(dest_provisional_grade) end def publish_rubric_assessments! - self.rubric_assessments.each do |provisional_assessment| + rubric_assessments.each do |provisional_assessment| rubric_association = provisional_assessment.active_rubric_association? ? provisional_assessment.rubric_association : nil # This case arises when a rubric is deleted. next if rubric_association.nil? @@ -198,7 +196,7 @@ def publish_rubric_assessments! rubric_assessment ||= rubric_association.rubric_assessments.build( params.merge( assessor: provisional_assessment.assessor, - user: self.student, + user: student, rubric: rubric_association.rubric ) ) @@ -212,7 +210,7 @@ def publish_rubric_assessments! end def infer_grade - if self.score.present? && self.grade.nil? + if score.present? && grade.nil? self.grade = submission.assignment.score_to_grade(score) end end diff --git a/app/models/notification.rb b/app/models/notification.rb index 4f33e137a5215..a128a9ee62260 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -154,7 +154,7 @@ class Notification < Switchman::UnshardedRecord end def self.all_cached - @all ||= self.all.to_a.each(&:readonly!) + @all ||= all.to_a.each(&:readonly!) end def self.valid_configurable_types @@ -186,8 +186,8 @@ def self.reset_cache! end def duplicate - notification = self.clone - notification.id = self.id + notification = clone + notification.id = id notification.send(:remove_instance_variable, :@new_record) notification end @@ -212,7 +212,7 @@ def create_message(asset, to_list, options = {}) TYPES_TO_PRELOAD_CONTEXT_ROLES = ["Assignment Created", "Assignment Due Date Changed"].freeze def preload_asset_roles_if_needed(asset) - if TYPES_TO_PRELOAD_CONTEXT_ROLES.include?(self.name) + if TYPES_TO_PRELOAD_CONTEXT_ROLES.include?(name) case asset when Assignment ActiveRecord::Associations::Preloader.new.preload(asset, :assignment_overrides) @@ -258,31 +258,31 @@ def self.types_to_send_in_push end def show_in_feed? - self.category == "TestImmediately" || Notification.types_to_show_in_feed.include?(self.name) + category == "TestImmediately" || Notification.types_to_show_in_feed.include?(name) end def is_course_type? - COURSE_TYPES.include? self.category + COURSE_TYPES.include? category end def registration? - self.category == "Registration" + category == "Registration" end def migration? - self.category == "Migration" + category == "Migration" end def summarizable? - !self.registration? && !self.migration? + !registration? && !migration? end def dashboard? - NON_CONFIGURABLE_TYPES.exclude?(self.category) + NON_CONFIGURABLE_TYPES.exclude?(category) end def category_slug - (self.category || "").tr(' ', "_").gsub(/[^\w]/, "").downcase + (category || "").tr(' ', "_").gsub(/[^\w]/, "").downcase end # if user is given, categories that aren't relevant to that user will be @@ -301,7 +301,7 @@ def self.dashboard_categories(user = nil) # Return a hash with information for a related user option if one exists. def related_user_setting(user, root_account) - if user.present? && self.category == 'Grading' && root_account.settings[:allow_sending_scores_in_emails] != false + if user.present? && category == 'Grading' && root_account.settings[:allow_sending_scores_in_emails] != false { name: :send_scores_in_emails, value: user.preferences[:send_scores_in_emails], @@ -309,7 +309,7 @@ def related_user_setting(user, root_account) Include scores when alerting about grades. If your email is not an institution email this means sensitive content will be sent outside of the institution. TEXT - id: "cat_#{self.id}_option", + id: "cat_#{id}_option", } end end diff --git a/app/models/notification_endpoint.rb b/app/models/notification_endpoint.rb index fb347c2a73f68..97a4bfa384fa4 100644 --- a/app/models/notification_endpoint.rb +++ b/app/models/notification_endpoint.rb @@ -35,7 +35,7 @@ class FailedSnsInteraction < StandardError; end def push_json(json) return false unless endpoint_exists? && own_endpoint? && endpoint_enabled? && !token_changed? - sns_client.publish(target_arn: self.arn, message: json, message_structure: 'json') + sns_client.publish(target_arn: arn, message: json, message_structure: 'json') end private @@ -47,7 +47,7 @@ def sns_client end def endpoint_attributes - @endpoint_attributes ||= sns_client.get_endpoint_attributes(endpoint_arn: self.arn).attributes + @endpoint_attributes ||= sns_client.get_endpoint_attributes(endpoint_arn: arn).attributes end def endpoint_exists? @@ -66,7 +66,7 @@ def endpoint_enabled? end def token_changed? - self.token != endpoint_attributes['Token'] + token != endpoint_attributes['Token'] end def create_platform_endpoint @@ -75,7 +75,7 @@ def create_platform_endpoint begin response = sns_client.create_platform_endpoint( platform_application_arn: access_token.developer_key.sns_arn, - token: self.token, + token: token, custom_user_data: access_token.global_id.to_s ) self.arn = response[:endpoint_arn] @@ -89,7 +89,7 @@ def create_platform_endpoint endpoint_updated = false begin sns_client.set_endpoint_attributes( - endpoint_arn: self.arn, + endpoint_arn: arn, attributes: { 'CustomUserData' => access_token.global_id.to_s } ) endpoint_updated = true @@ -115,6 +115,6 @@ def create_platform_endpoint def delete_platform_endpoint return unless endpoint_exists? && own_endpoint? - sns_client.delete_endpoint(endpoint_arn: self.arn) + sns_client.delete_endpoint(endpoint_arn: arn) end end diff --git a/app/models/notification_failure_processor.rb b/app/models/notification_failure_processor.rb index 427ac8b6adb81..8acbd14426b68 100644 --- a/app/models/notification_failure_processor.rb +++ b/app/models/notification_failure_processor.rb @@ -40,11 +40,11 @@ def self.config end def self.enabled? - !!self.config + !!config end def self.process - self.new.process + new.process end def initialize diff --git a/app/models/notification_preloader.rb b/app/models/notification_preloader.rb index e2569043a18be..cb740be84b6a2 100644 --- a/app/models/notification_preloader.rb +++ b/app/models/notification_preloader.rb @@ -25,8 +25,8 @@ def self.included(klass) end def preload_notification - if self.notification_id - self.notification = Notification.find(self.notification_id) + if notification_id + self.notification = Notification.find(notification_id) end end end diff --git a/app/models/observer_alert_threshold.rb b/app/models/observer_alert_threshold.rb index 3c61a8dc3aeab..fa24ca5b4ab87 100644 --- a/app/models/observer_alert_threshold.rb +++ b/app/models/observer_alert_threshold.rb @@ -64,12 +64,12 @@ def users_are_still_linked? # Also enforces _not_ passing a threshold if one is not required def validate_threshold_type # If a threshold is provided, there are only 4 applicable types of alert - if self.threshold - unless ALERT_TYPES_WITH_THRESHOLD.include? self.alert_type + if threshold + unless ALERT_TYPES_WITH_THRESHOLD.include? alert_type errors.add(:threshold, "Threshold is only applicable to the following alert types: #{ALERT_TYPES_WITH_THRESHOLD.join(', ')}") end else - unless ALERT_TYPES_WITHOUT_THRESHOLD.include? self.alert_type + unless ALERT_TYPES_WITHOUT_THRESHOLD.include? alert_type errors.add(:threshold, "Threshold is required for the provided alert_type.") end end @@ -80,18 +80,18 @@ def validate_threshold_type # If the user sets assignment_grade_high to be 40, and then tries to set assignment_grade_low to 50, that would be rejected. # On the flip side, if assignment_grade_low is set to 50, and then assignment_grade_high is set to 20, will be rejected def validate_threshold_low_high - if ALERT_TYPES_WITH_THRESHOLD.include? self.alert_type - opposite_type = if self.alert_type.include? 'high' - self.alert_type.gsub('high', 'low') + if ALERT_TYPES_WITH_THRESHOLD.include? alert_type + opposite_type = if alert_type.include? 'high' + alert_type.gsub('high', 'low') else - self.alert_type.gsub('low', 'high') + alert_type.gsub('low', 'high') end opposite = observer.as_observer_observer_alert_thresholds.where(alert_type: opposite_type) if opposite.any? - if (self.alert_type.include? 'high') && (self.threshold.to_i <= opposite.first.threshold.to_i) + if (alert_type.include? 'high') && (threshold.to_i <= opposite.first.threshold.to_i) errors.add(:threshold, 'You cannot set a high threshold that is lower or equal to a previously set low threshold.') - elsif (self.alert_type.include? 'low') && (self.threshold.to_i >= opposite.first.threshold.to_i) + elsif (alert_type.include? 'low') && (threshold.to_i >= opposite.first.threshold.to_i) errors.add(:threshold, 'You cannot set a low threshold that is higher or equal to a previously set high threshold.') end end @@ -100,14 +100,14 @@ def validate_threshold_low_high def destroy self.workflow_state = 'deleted' - self.save! + save! end def did_pass_threshold(previous_value, new_value) - t = self.threshold.to_i - if self.alert_type.include? 'high' + t = threshold.to_i + if alert_type.include? 'high' (previous_value.nil? || previous_value < t) && (!new_value.nil? && new_value > t) - elsif self.alert_type.include? 'low' + elsif alert_type.include? 'low' (previous_value.nil? || previous_value > t) && (!new_value.nil? && new_value < t) end end diff --git a/app/models/observer_pairing_code.rb b/app/models/observer_pairing_code.rb index da0d82135e127..62220a00a64c9 100644 --- a/app/models/observer_pairing_code.rb +++ b/app/models/observer_pairing_code.rb @@ -26,6 +26,6 @@ class ObserverPairingCode < ActiveRecord::Base def destroy self.workflow_state = 'deleted' - self.save! + save! end end diff --git a/app/models/originality_report.rb b/app/models/originality_report.rb index 9c8518a942867..ff619102cef07 100644 --- a/app/models/originality_report.rb +++ b/app/models/originality_report.rb @@ -89,7 +89,7 @@ def asset_key end def self.copy_to_group_submissions!(report_id:, user_id:) - report = self.find(report_id) + report = find(report_id) report.copy_to_group_submissions! rescue ActiveRecord::RecordNotFound => e user = User.where(id: user_id).first @@ -109,7 +109,7 @@ def copy_to_group_submissions! group_submissions = assignment.submissions.where.not(id: submission.id).where(group: submission.group) group_submissions.find_each do |s| - copy_of_report = self.dup + copy_of_report = dup copy_of_report.submission_time = nil # We don't want a single submission to have @@ -139,9 +139,9 @@ def set_submission_time def infer_workflow_state self.workflow_state = 'error' if error_message.present? - return if self.workflow_state == 'error' + return if workflow_state == 'error' - self.workflow_state = self.originality_score.present? ? 'scored' : 'pending' + self.workflow_state = originality_score.present? ? 'scored' : 'pending' end def set_root_account diff --git a/app/models/outcome_import.rb b/app/models/outcome_import.rb index 2097d52fbb186..1e072b4f962ef 100644 --- a/app/models/outcome_import.rb +++ b/app/models/outcome_import.rb @@ -73,15 +73,15 @@ def self.create_with_attachment(context, import_type, attachment, user = nil, le def as_json(_options = {}) data = { - "id" => self.id, - "created_at" => self.created_at, - "ended_at" => self.ended_at, - "updated_at" => self.updated_at, - "progress" => self.progress, - "workflow_state" => self.workflow_state, + "id" => id, + "created_at" => created_at, + "ended_at" => ended_at, + "updated_at" => updated_at, + "progress" => progress, + "workflow_state" => workflow_state, "data" => self.data } - data["processing_errors"] = self.outcome_import_errors.order(:row).limit(25).pluck(:row, :message) + data["processing_errors"] = outcome_import_errors.order(:row).limit(25).pluck(:row, :message) data end @@ -103,13 +103,13 @@ def run root_account.shard.activate do job_started! I18n.locale = locale if locale.present? - file = self.attachment.open(need_local_file: true) + file = attachment.open(need_local_file: true) Outcomes::CSVImporter.new(self, file).run do |status| status[:errors].each do |row, error| add_error row, error end - self.update!(progress: status[:progress]) + update!(progress: status[:progress]) end job_completed! diff --git a/app/models/outcome_proficiency.rb b/app/models/outcome_proficiency.rb index 1a16edcff659f..f07f669a9af45 100644 --- a/app/models/outcome_proficiency.rb +++ b/app/models/outcome_proficiency.rb @@ -45,7 +45,7 @@ def self.emit_live_events_on_any_update? alias_method :original_destroy_permanently!, :destroy_permanently! private :original_destroy_permanently! def destroy_permanently! - self.outcome_proficiency_ratings.delete_all + outcome_proficiency_ratings.delete_all original_destroy_permanently! end @@ -54,14 +54,14 @@ def destroy_permanently! def undestroy transaction do OutcomeProficiencyRating.where(outcome_proficiency: self).update_all(workflow_state: 'active', updated_at: Time.zone.now.utc) - self.reload + reload original_undestroy end end def as_json(_options = {}) { - 'ratings' => self.outcome_proficiency_ratings.map(&:as_json) + 'ratings' => outcome_proficiency_ratings.map(&:as_json) } end @@ -117,7 +117,7 @@ def self.find_or_create_default!(context) OutcomeProficiency.transaction do proficiency ||= OutcomeProficiency.new(context: context) proficiency.workflow_state = 'active' - proficiency.replace_ratings(self.default_ratings) + proficiency.replace_ratings(default_ratings) proficiency.save! proficiency end @@ -133,19 +133,19 @@ def self.find_or_create_default!(context) private def next_ratings - self.outcome_proficiency_ratings.reject(&:marked_for_destruction?) + outcome_proficiency_ratings.reject(&:marked_for_destruction?) end def single_mastery_rating if next_ratings.count(&:mastery) != 1 - self.errors.add(:outcome_proficiency_ratings, t('Exactly one rating can have mastery')) + errors.add(:outcome_proficiency_ratings, t('Exactly one rating can have mastery')) end end def strictly_decreasing_points next_ratings.each_cons(2) do |l, r| if l.points <= r.points - self.errors.add( + errors.add( :outcome_proficiency_ratings, t("Points should be strictly decreasing: %{l} <= %{r}", l: l.points, r: r.points) ) @@ -160,7 +160,7 @@ def clear_cached_proficiencies end def detect_changes_for_rubrics - @update_rubrics = self.changed_for_autosave? + @update_rubrics = changed_for_autosave? end def propagate_changes_to_rubrics diff --git a/app/models/outcome_proficiency_rating.rb b/app/models/outcome_proficiency_rating.rb index 661c9c841e411..898ac85f68f28 100644 --- a/app/models/outcome_proficiency_rating.rb +++ b/app/models/outcome_proficiency_rating.rb @@ -32,8 +32,8 @@ class OutcomeProficiencyRating < ApplicationRecord alias_method :original_destroy, :destroy private :original_destroy def destroy - if self.marked_for_destruction? - self.destroy_permanently! + if marked_for_destruction? + destroy_permanently! else original_destroy end @@ -41,10 +41,10 @@ def destroy def as_json(_options = {}) {}.tap do |h| - h['description'] = self.description - h['points'] = self.points - h['mastery'] = self.mastery - h['color'] = self.color + h['description'] = description + h['points'] = points + h['mastery'] = mastery + h['color'] = color end end end diff --git a/app/models/pace_plan.rb b/app/models/pace_plan.rb index ebba421d45959..044b0de457583 100644 --- a/app/models/pace_plan.rb +++ b/app/models/pace_plan.rb @@ -51,7 +51,7 @@ class PacePlan < ActiveRecord::Base end set_policy do - given { |user, session| self.course.grants_right?(user, session, :manage) } + given { |user, session| course.grants_right?(user, session, :manage) } can :read end @@ -59,7 +59,7 @@ class PacePlan < ActiveRecord::Base def valid_secondary_context if course_section_id.present? && user_id.present? - self.errors.add(:base, "Only one of course_section_id and user_id can be given") + errors.add(:base, "Only one of course_section_id and user_id can be given") end end @@ -70,10 +70,10 @@ def duplicate(opts = {}) published_at: nil, workflow_state: 'unpublished' } - pace_plan = self.dup + pace_plan = dup pace_plan.attributes = default_opts.merge(opts) - self.pace_plan_module_items.each do |pace_plan_module_item| + pace_plan_module_items.each do |pace_plan_module_item| pace_plan.pace_plan_module_items.new( module_item_id: pace_plan_module_item.module_item_id, duration: pace_plan_module_item.duration, diff --git a/app/models/pace_plan_module_item.rb b/app/models/pace_plan_module_item.rb index 2c39db8be113f..9b95533699e0f 100644 --- a/app/models/pace_plan_module_item.rb +++ b/app/models/pace_plan_module_item.rb @@ -38,7 +38,7 @@ class PacePlanModuleItem < ActiveRecord::Base def assignable_module_item unless module_item&.assignment - self.errors.add(:module_item, 'is not assignable') + errors.add(:module_item, 'is not assignable') end end end diff --git a/app/models/page_comment.rb b/app/models/page_comment.rb index d19d5077865f3..7a866ba183d94 100644 --- a/app/models/page_comment.rb +++ b/app/models/page_comment.rb @@ -26,6 +26,6 @@ class PageComment < ActiveRecord::Base scope :for_user, lambda { |user| where(:user_id => user) } def user_name - self.user.name rescue t(:default_user_name, "Anonymous") + user.name rescue t(:default_user_name, "Anonymous") end end diff --git a/app/models/page_view.rb b/app/models/page_view.rb index 08ce9b41e391f..3bf635e2e0776 100644 --- a/app/models/page_view.rb +++ b/app/models/page_view.rb @@ -43,7 +43,7 @@ class PageView < ActiveRecord::Base validates :user_id, presence: true def self.generate(request, attributes = {}) - self.new(attributes).tap do |p| + new(attributes).tap do |p| p.url = LoggingFilter.filter_uri(request.url)[0, 255] p.http_method = request.request_method.downcase p.controller = request.path_parameters[:controller] @@ -65,7 +65,7 @@ def self.generate(request, attributes = {}) end def self.find_for_update(request_id) - if PageView.updates_enabled? && (self.db? || self.cassandra?) + if PageView.updates_enabled? && (db? || cassandra?) begin # not using find_by_id or where(..).first because the cassandra # codepath doesn't support it @@ -92,12 +92,12 @@ def url end def ensure_account - self.account_id ||= (self.context_type == 'Account' ? self.context_id : self.context.account_id) rescue nil - self.account_id ||= (self.context.is_a?(Account) ? self.context : self.context.account) if self.context + self.account_id ||= (context_type == 'Account' ? context_id : context.account_id) rescue nil + self.account_id ||= (context.is_a?(Account) ? context : context.account) if context end def cap_interaction_seconds - self.interaction_seconds = [self.interaction_seconds || 5, 10.minutes.to_i].min + self.interaction_seconds = [interaction_seconds || 5, 10.minutes.to_i].min end # the list of columns we display to users, export to csv, etc @@ -126,7 +126,7 @@ def initialize_shard end def self.db? - self.page_view_method == :db + page_view_method == :db end def self.cassandra? @@ -224,19 +224,19 @@ def self.updates_enabled? def store self.created_at ||= Time.zone.now return false unless user - return false if self.is_update && !PageView.updates_enabled? + return false if is_update && !PageView.updates_enabled? result = case PageView.page_view_method when :log - Rails.logger.info "PAGE VIEW: #{self.attributes.to_json}" + Rails.logger.info "PAGE VIEW: #{attributes.to_json}" when :db self.shard = user.shard if new_record? - self.save + save when :cassandra - self.save + save end - self.store_page_view_to_user_counts + store_page_view_to_user_counts result end @@ -248,7 +248,7 @@ def do_update(params = {}) shard.activate do updated_at = params['updated_at'] || self.updated_at || Time.now updated_at = Time.parse(updated_at) if updated_at.is_a?(String) - seconds = self.interaction_seconds || 0 + seconds = interaction_seconds || 0 if params['interaction_seconds'].to_i > 0 seconds += params['interaction_seconds'].to_i else @@ -269,7 +269,7 @@ def _create_record(*args) run_callbacks(:create) do PageView::EventStream.insert(self) @new_record = false - self.id + id end end changes_applied @@ -313,7 +313,7 @@ def self.for_user(user, options = {}) result = AccountFilter.filter(result, viewer) if viewer result else - scope = self.where(:user_id => user).order('created_at desc') + scope = where(:user_id => user).order('created_at desc') scope = scope.where("created_at >= ?", options[:oldest]) if options[:oldest] scope = scope.where("created_at <= ?", options[:newest]) if options[:newest] if viewer @@ -380,11 +380,11 @@ def self.active_user_counts_by_shard(time = Time.now) def store_page_view_to_user_counts return unless Setting.get('page_views_store_active_user_counts', 'false') == 'redis' && Canvas.redis_enabled? - return unless self.created_at.present? && self.user.present? + return unless self.created_at.present? && user.present? exptime = Setting.get('page_views_active_user_exptime', 1.day.to_s).to_i bucket = PageView.user_count_bucket_for_time(self.created_at) - Canvas.redis.sadd(bucket, self.user.global_id) + Canvas.redis.sadd(bucket, user.global_id) Canvas.redis.expire(bucket, exptime) end @@ -394,7 +394,7 @@ def export_columns end def to_row - export_columns.map { |c| self.send(c).presence } + export_columns.map { |c| send(c).presence } end def app_name @@ -420,11 +420,11 @@ def initialize(skip_deleted_accounts = true, start_at = nil) def load_migration_data(account_ids) self.migration_data = {} account_ids.each do |account_id| - data = self.migration_data[account_id] = {} + data = migration_data[account_id] = {} data.merge!(cassandra.execute("SELECT last_created_at FROM page_views_migration_metadata_per_account WHERE shard_id = ? AND account_id = ?", Shard.current.id.to_s, account_id).fetch.try(:to_hash) || {}) unless data['last_created_at'] - data['last_created_at'] = self.start_at + data['last_created_at'] = start_at end # cassandra returns Time not TimeWithZone objects data['last_created_at'] = data['last_created_at'].in_time_zone @@ -434,13 +434,13 @@ def load_migration_data(account_ids) # this is the batch size per account, not the overall batch size # returns true if any progress was made (if it makes sense to run_once again) def run_once(batch_size = 3000) - self.migration_data.inject(false) do |progress, (account_id, _)| + migration_data.inject(false) do |progress, (account_id, _)| run_once_for_account(account_id, batch_size) || progress end end def run_once_for_account(account_id, batch_size) - data = self.migration_data[account_id] + data = migration_data[account_id] raise("not configured for account id: #{account_id}") unless data last_created_at = data['last_created_at'] diff --git a/app/models/parallel_importer.rb b/app/models/parallel_importer.rb index e70038ba8f468..5f7516ec3de38 100644 --- a/app/models/parallel_importer.rb +++ b/app/models/parallel_importer.rb @@ -40,22 +40,22 @@ class ParallelImporter < ActiveRecord::Base def start if workflow_state == 'retry' - self.update!(started_at: Time.now.utc) + update!(started_at: Time.now.utc) else - self.update!(:workflow_state => "running", :started_at => Time.now.utc) + update!(:workflow_state => "running", :started_at => Time.now.utc) end end def fail - self.update!(:workflow_state => "failed", :ended_at => Time.now.utc) + update!(:workflow_state => "failed", :ended_at => Time.now.utc) end def abort - self.update!(:workflow_state => "aborted", :ended_at => Time.now.utc) + update!(:workflow_state => "aborted", :ended_at => Time.now.utc) end def complete(opts = {}) updates = { :workflow_state => "completed", :ended_at => Time.now.utc }.merge(opts) - self.update!(updates) + update!(updates) end end diff --git a/app/models/planner_override.rb b/app/models/planner_override.rb index e668d332453c4..093a88f67ab66 100644 --- a/app/models/planner_override.rb +++ b/app/models/planner_override.rb @@ -50,16 +50,16 @@ class PlannerOverride < ActiveRecord::Base alias_method :published?, :active? def link_to_parent_topic - return unless self.plannable_type == 'DiscussionTopic' + return unless plannable_type == 'DiscussionTopic' - plannable = DiscussionTopic.find(self.plannable_id) + plannable = DiscussionTopic.find(plannable_id) self.plannable_id = plannable.root_topic_id if plannable.root_topic_id end def link_to_submittable - return unless self.plannable_type == 'Assignment' + return unless plannable_type == 'Assignment' - plannable = Assignment.find_by(id: self.plannable_id) + plannable = Assignment.find_by(id: plannable_id) if plannable&.quiz? self.plannable_type = PlannerHelper::PLANNABLE_TYPES['quiz'] self.plannable_id = plannable.quiz.id @@ -73,9 +73,9 @@ def link_to_submittable end def associated_assignment_id - return self.plannable_id if self.plannable_type == 'Assignment' + return plannable_id if plannable_type == 'Assignment' - self.plannable.assignment_id if self.plannable.respond_to? :assignment_id + plannable.assignment_id if plannable.respond_to? :assignment_id end def self.update_for(obj) @@ -107,13 +107,13 @@ def self.plannable_workflow_state(plannable) end def plannable_workflow_state - PlannerOverride.plannable_workflow_state(self.plannable) + PlannerOverride.plannable_workflow_state(plannable) end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - self.save + save end end diff --git a/app/models/plugin_setting.rb b/app/models/plugin_setting.rb index fc9416fe0b5a7..1750e1efb1514 100644 --- a/app/models/plugin_setting.rb +++ b/app/models/plugin_setting.rb @@ -62,12 +62,12 @@ def plugin # it's set) and be able to tell when it gets blanked out. DUMMY_STRING = "~!?3NCRYPT3D?!~" def initialize_plugin_setting - return unless settings && self.plugin + return unless settings && plugin @valid_settings = true - if self.plugin.encrypted_settings - was_dirty = self.changed? - self.plugin.encrypted_settings.each do |key| + if plugin.encrypted_settings + was_dirty = changed? + plugin.encrypted_settings.each do |key| if settings["#{key}_enc".to_sym] begin settings["#{key}_dec".to_sym] = self.class.decrypt(settings["#{key}_enc".to_sym], settings["#{key}_salt".to_sym]) @@ -78,7 +78,7 @@ def initialize_plugin_setting end end # We shouldn't consider a plugin setting to be dirty if all that changed were the decrypted/placeholder attributes - self.clear_changes_information unless was_dirty + clear_changes_information unless was_dirty end end @@ -87,8 +87,8 @@ def valid_settings? end def encrypt_settings - if settings && self.plugin && self.plugin.encrypted_settings - self.plugin.encrypted_settings.each do |key| + if settings && plugin && plugin.encrypted_settings + plugin.encrypted_settings.each do |key| unless settings[key].blank? value = settings.delete(key) settings.delete("#{key}_dec".to_sym) @@ -139,7 +139,7 @@ def self.settings_cache_key(name) def clear_cache self.class.connection.after_transaction_commit do - MultiCache.delete(PluginSetting.settings_cache_key(self.name)) + MultiCache.delete(PluginSetting.settings_cache_key(name)) end end diff --git a/app/models/polling/poll.rb b/app/models/polling/poll.rb index d95c0baf330d6..cd645c04a0013 100644 --- a/app/models/polling/poll.rb +++ b/app/models/polling/poll.rb @@ -37,7 +37,7 @@ class Poll < ActiveRecord::Base can :create given do |user, http_session| - self.poll_sessions.shard(self).preload(:course).any? do |session| + poll_sessions.shard(self).preload(:course).any? do |session| session.course.grants_right?(user, http_session, :manage_content) end end @@ -45,7 +45,7 @@ class Poll < ActiveRecord::Base given do |user| can_read = false - self.poll_sessions.shard(self).activate do |scope| + poll_sessions.shard(self).activate do |scope| if scope.where(["course_id IN (?) AND (course_section_id IS NULL OR course_section_id IN (?))", Enrollment.where(user_id: user).active.select(:course_id), Enrollment.where(user_id: user).active.select(:course_section_id)]).exists? diff --git a/app/models/polling/poll_session.rb b/app/models/polling/poll_session.rb index d335f5b14caee..75abab8c2b706 100644 --- a/app/models/polling/poll_session.rb +++ b/app/models/polling/poll_session.rb @@ -29,17 +29,17 @@ class PollSession < ActiveRecord::Base set_policy do given do |user, session| - self.poll.grants_right?(user, session, :update) + poll.grants_right?(user, session, :update) end can :read and can :create and can :delete and can :publish given do |user, session| - self.visible_to?(user, session) + visible_to?(user, session) end can :read given do |user, session| - self.visible_to?(user, session) && self.is_published? + visible_to?(user, session) && is_published? end can :submit end @@ -69,15 +69,15 @@ def close! end def visible_to?(user, session) - self.course.grants_right?(user, session, :read) && - (self.course_section ? self.course_section.grants_right?(user, session, :read) : true) + course.grants_right?(user, session, :read) && + (course_section ? course_section.grants_right?(user, session, :read) : true) end private def section_belongs_to_course - if self.course && self.course_section - unless self.course.course_sections.include?(course_section) + if course && course_section + unless course.course_sections.include?(course_section) errors.add(:base, I18n.t('polling.poll_sessions.validations.section_belongs_to_course', 'That course section does not belong to the existing course.')) end diff --git a/app/models/polling/poll_submission.rb b/app/models/polling/poll_submission.rb index 195f8531363db..f3e5924607585 100644 --- a/app/models/polling/poll_submission.rb +++ b/app/models/polling/poll_submission.rb @@ -40,12 +40,12 @@ class PollSubmission < ActiveRecord::Base set_policy do given do |user, session| - self.poll.grants_right?(user, session, :update) || self.user == user + poll.grants_right?(user, session, :update) || self.user == user end can :read given do |user, session| - self.poll_session.grants_right?(user, session, :submit) + poll_session.grants_right?(user, session, :submit) end can :submit end @@ -53,8 +53,8 @@ class PollSubmission < ActiveRecord::Base private def poll_is_published - if self.poll_session - unless self.poll_session.is_published? + if poll_session + unless poll_session.is_published? errors.add(:base, I18n.t('polling.poll_submissions.validations.poll_is_published', 'This poll session is not open for submissions.')) end @@ -62,8 +62,8 @@ def poll_is_published end def poll_choices_belong_to_poll - if self.poll - unless self.poll.poll_choices.include?(poll_choice) + if poll + unless poll.poll_choices.include?(poll_choice) errors.add(:base, I18n.t('polling.poll_submissions.validations.poll_choice_belongs_to_poll', 'That poll choice does not belong to the existing poll.')) end diff --git a/app/models/progress.rb b/app/models/progress.rb index 732dd802cd850..50671564f4e23 100644 --- a/app/models/progress.rb +++ b/app/models/progress.rb @@ -50,12 +50,12 @@ def reset! self.results = nil self.workflow_state = 'queued' self.completion = 0 - GuardRail.activate(:primary) { self.save! } + GuardRail.activate(:primary) { save! } end def set_results(results) self.results = results - self.save + save end def update_completion!(value) @@ -111,7 +111,7 @@ def initialize(progress, *args, **kwargs) end def perform - self.args[0] = @progress if self.args[0] == @progress # maintain the same object reference + args[0] = @progress if args[0] == @progress # maintain the same object reference @progress.start super @progress.reload diff --git a/app/models/pseudonym.rb b/app/models/pseudonym.rb index e863e5157ad81..334afaf10bde7 100644 --- a/app/models/pseudonym.rb +++ b/app/models/pseudonym.rb @@ -108,51 +108,51 @@ def require_password? set_broadcast_policy do |p| p.dispatch :confirm_registration - p.to { self.communication_channel || self.user.communication_channel } + p.to { communication_channel || user.communication_channel } p.whenever { @send_confirmation } p.dispatch :pseudonym_registration - p.to { self.communication_channel || self.user.communication_channel } + p.to { communication_channel || user.communication_channel } p.whenever { @send_registration_notification } p.dispatch :pseudonym_registration_done - p.to { self.communication_channel || self.user.communication_channel } + p.to { communication_channel || user.communication_channel } p.whenever { @send_registration_done_notification } end def update_account_associations_if_account_changed - return unless self.user && !User.skip_updating_account_associations? + return unless user && !User.skip_updating_account_associations? - if self.id_before_last_save.nil? - return if %w[creation_pending deleted].include?(self.user.workflow_state) + if id_before_last_save.nil? + return if %w[creation_pending deleted].include?(user.workflow_state) - self.user.update_account_associations(:incremental => true, :precalculated_associations => { self.account_id => 0 }) - elsif self.saved_change_to_account_id? - self.user.update_account_associations_later + user.update_account_associations(:incremental => true, :precalculated_associations => { account_id => 0 }) + elsif saved_change_to_account_id? + user.update_account_associations_later end end def must_be_root_account if account_id_changed? - self.errors.add(:account_id, "must belong to a root_account") unless account.root_account? + errors.add(:account_id, "must belong to a root_account") unless account.root_account? end end def send_registration_notification! @send_registration_notification = true - self.save! + save! @send_registration_notification = false end def send_registration_done_notification! @send_registration_done_notification = true - self.save! + save! @send_registration_done_notification = false end def send_confirmation! @send_confirmation = true - self.save! + save! @send_confirmation = false end @@ -174,7 +174,7 @@ def self.for_auth_configuration(unique_id, aac) end def set_password_changed - @password_changed = self.password && self.password_confirmation == self.password + @password_changed = password && password_confirmation == password end def password=(new_pass) @@ -183,29 +183,29 @@ def password=(new_pass) end def communication_channel - self.user.communication_channels.by_path(self.unique_id).first + user.communication_channels.by_path(unique_id).first end def confirmation_code - (self.communication_channel || self.user.communication_channel).confirmation_code + (communication_channel || user.communication_channel).confirmation_code end def infer_defaults self.account ||= Account.default if (!crypted_password || crypted_password == "") && !@require_password - self.generate_temporary_password + generate_temporary_password end # treat empty or whitespaced strings as nullable - self.integration_id = nil if self.integration_id.blank? - self.sis_user_id = nil if self.sis_user_id.blank? + self.integration_id = nil if integration_id.blank? + self.sis_user_id = nil if sis_user_id.blank? end def login_assertions_for_user - if !self.persistence_token || self.persistence_token == '' + if !persistence_token || persistence_token == '' # Some pseudonyms can end up without a persistence token if they were created # using the SIS, for example. self.persistence_token = CanvasSlug.generate('pseudo', 15) - self.save + save end user = self.user @@ -233,7 +233,7 @@ def works_for_account?(_account, _allow_implicit = false, ignore_types: [:implic end def <=>(other) - self.position <=> other.position + position <=> other.position end def retire_channels @@ -241,19 +241,19 @@ def retire_channels end def validate_unique_id - if (!self.account || self.account.email_pseudonyms) && !self.deleted? - unless self.unique_id.present? && EmailAddressValidator.valid?(self.unique_id) - self.errors.add(:unique_id, "not_email") + if (!self.account || self.account.email_pseudonyms) && !deleted? + unless unique_id.present? && EmailAddressValidator.valid?(unique_id) + errors.add(:unique_id, "not_email") throw :abort end end - unless self.deleted? - self.shard.activate do - existing_pseudo = Pseudonym.active.by_unique_id(self.unique_id).where(:account_id => self.account_id, - :authentication_provider_id => self.authentication_provider_id).where.not(id: self).exists? + unless deleted? + shard.activate do + existing_pseudo = Pseudonym.active.by_unique_id(unique_id).where(:account_id => account_id, + :authentication_provider_id => authentication_provider_id).where.not(id: self).exists? if existing_pseudo - self.errors.add(:unique_id, :taken, - message: t("ID already in use for this account and authentication provider")) + errors.add(:unique_id, :taken, + message: t("ID already in use for this account and authentication provider")) throw :abort end end @@ -262,20 +262,20 @@ def validate_unique_id end def verify_unique_sis_user_id - return true unless self.sis_user_id - return true unless Pseudonym.where.not(id: id).where(account_id: self.account_id, sis_user_id: self.sis_user_id).exists? + return true unless sis_user_id + return true unless Pseudonym.where.not(id: id).where(account_id: account_id, sis_user_id: sis_user_id).exists? - self.errors.add(:sis_user_id, :taken, - message: t('#errors.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", sis_id: self.sis_user_id)) + errors.add(:sis_user_id, :taken, + message: t('#errors.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", sis_id: sis_user_id)) throw :abort end def verify_unique_integration_id - return true unless self.integration_id - return true unless Pseudonym.where.not(id: id).where(account_id: self.account_id, integration_id: self.integration_id).exists? + return true unless integration_id + return true unless Pseudonym.where.not(id: id).where(account_id: account_id, integration_id: integration_id).exists? - self.errors.add(:integration_id, :taken, - message: t("Integration ID \"%{integration_id}\" is already in use", integration_id: self.integration_id)) + errors.add(:integration_id, :taken, + message: t("Integration ID \"%{integration_id}\" is already in use", integration_id: integration_id)) throw :abort end @@ -331,7 +331,7 @@ def verify_unique_integration_id # permission on the pseudonym's account given do |user| self.account.grants_right?(user, :manage_sis) && - self.grants_right?(user, :update) + grants_right?(user, :update) end can :manage_sis @@ -352,17 +352,17 @@ def verify_unique_integration_id def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - result = self.save - self.user.try(:update_account_associations) if result + result = save + user.try(:update_account_associations) if result result end def never_logged_in? - !self.login_count || self.login_count == 0 + !login_count || login_count == 0 end def user_code - self.user.uuid rescue nil + user.uuid rescue nil end def email @@ -370,13 +370,13 @@ def email end def email_channel - self.communication_channel if self.communication_channel && self.communication_channel.path_type == 'email' + communication_channel if communication_channel && communication_channel.path_type == 'email' end def email=(e) return unless user - self.user.email = (e) + user.email = (e) user.save! user.email end @@ -388,7 +388,7 @@ def sms def sms=(s) return unless user - self.user.sms = (s) + user.sms = (s) user.save! user.sms end @@ -411,7 +411,7 @@ def managed_password? !authentication_provider.is_a?(AuthenticationProvider::Canvas) else # otherwise we have to guess - !!(self.sis_user_id && account.non_canvas_auth_configured?) + !!(sis_user_id && account.non_canvas_auth_configured?) end end @@ -437,15 +437,15 @@ def valid_arbitrary_credentials?(plaintext_password) end def generate_temporary_password - self.reset_password + reset_password self.password_auto_generated = true - self.password + password end def valid_ssha?(plaintext_password) - return false if plaintext_password.blank? || self.sis_ssha.blank? + return false if plaintext_password.blank? || sis_ssha.blank? - decoded = Base64.decode64(self.sis_ssha.delete_prefix('{SSHA}')) + decoded = Base64.decode64(sis_ssha.delete_prefix('{SSHA}')) digest = decoded[0, 40] salt = decoded[40..] return false unless digest && salt @@ -465,7 +465,7 @@ def ldap_bind_result(password_plaintext) [] end aps.each do |config| - res = config.ldap_bind_result(self.unique_id, password_plaintext) + res = config.ldap_bind_result(unique_id, password_plaintext) next unless res infer_auth_provider(config) @@ -480,13 +480,13 @@ def add_ldap_channel res = @ldap_result if res && res[:mail] && res[:mail][0] email = res[:mail][0] - cc = self.user.communication_channels.email.by_path(email).first - cc ||= self.user.communication_channels.build(:path => email) + cc = user.communication_channels.email.by_path(email).first + cc ||= user.communication_channels.build(:path => email) cc.workflow_state = 'active' - cc.user = self.user + cc.user = user cc.save if cc.changed? self.communication_channel = cc - self.save_without_session_maintenance if self.changed? + save_without_session_maintenance if changed? end end @@ -524,8 +524,8 @@ def valid_ldap_credentials?(password_plaintext) Canvas::Errors.capture(e, { type: :ldap, message: "LDAP authentication error", - object: self.inspect.to_s, - unique_id: self.unique_id, + object: inspect.to_s, + unique_id: unique_id, }) nil end diff --git a/app/models/pseudonym_session.rb b/app/models/pseudonym_session.rb index 158638ef11016..1700d264a834f 100644 --- a/app/models/pseudonym_session.rb +++ b/app/models/pseudonym_session.rb @@ -67,13 +67,13 @@ def persist_by_cookie if cookie token = SessionPersistenceToken.find_by_pseudonym_credentials(cookie) self.unauthorized_record = token.use! if token - is_valid = self.valid? + is_valid = valid? if is_valid # this token has been used -- destroy it, and generate a new one # remember_me is implicitly true when they login via the remember_me token controller.session[:used_remember_me_token] = true self.remember_me = true - self.save! + save! end is_valid else @@ -119,8 +119,8 @@ def too_many_attempts? # to know why your user that was previously logged in is now not # logged in. def self.find_with_validation - self.with_scope(find_options: Pseudonym.eager_load(:user)) do - sess = self.new({ priority_record: nil }, nil) + with_scope(find_options: Pseudonym.eager_load(:user)) do + sess = new({ priority_record: nil }, nil) if sess.nil? Rails.logger.info "[AUTH] Failed to create pseudonym session" return false diff --git a/app/models/purgatory.rb b/app/models/purgatory.rb index f18bd7e5fc637..8aec2b183fb7d 100644 --- a/app/models/purgatory.rb +++ b/app/models/purgatory.rb @@ -28,7 +28,7 @@ def self.days_until_expiration end def self.expire_old_purgatories - Purgatory.active.where("updated_at < ?", self.days_until_expiration.days.ago).find_in_batches do |batch| + Purgatory.active.where("updated_at < ?", days_until_expiration.days.ago).find_in_batches do |batch| batch.each do |p| if p.new_instfs_uuid begin diff --git a/app/models/quizzes/quiz.rb b/app/models/quizzes/quiz.rb index 386944b41fbf3..4e5a8e4f64ff4 100644 --- a/app/models/quizzes/quiz.rb +++ b/app/models/quizzes/quiz.rb @@ -65,7 +65,7 @@ class Quizzes::Quiz < ActiveRecord::Base quiz.hide_correct_answers_at_changed? } sanitize_field :description, CanvasSanitize::SANITIZE - copy_authorized_links(:description) { [self.context, nil] } + copy_authorized_links(:description) { [context, nil] } before_save :generate_quiz_data_on_publish, :if => :workflow_state_changed? before_save :build_assignment @@ -115,42 +115,42 @@ def current_version_unidirectional def infer_times # set the time to 11:59 pm in the creator's time zone, if none given - self.due_at = CanvasTime.fancy_midnight(self.due_at) - self.lock_at = CanvasTime.fancy_midnight(self.lock_at) + self.due_at = CanvasTime.fancy_midnight(due_at) + self.lock_at = CanvasTime.fancy_midnight(lock_at) end def set_defaults - self.cant_go_back = false unless self.one_question_at_a_time - unless self.show_correct_answers + self.cant_go_back = false unless one_question_at_a_time + unless show_correct_answers self.show_correct_answers_last_attempt = false self.show_correct_answers_at = nil self.hide_correct_answers_at = nil end - self.allowed_attempts = 1 if self.allowed_attempts.nil? - if self.allowed_attempts <= 1 + self.allowed_attempts = 1 if allowed_attempts.nil? + if allowed_attempts <= 1 self.show_correct_answers_last_attempt = false end - self.scoring_policy = "keep_highest" if self.scoring_policy.nil? - self.ip_filter = nil if self.ip_filter && self.ip_filter.strip.empty? - if !self.available? && !self.survey? - self.points_possible = self.current_points_possible + self.scoring_policy = "keep_highest" if scoring_policy.nil? + self.ip_filter = nil if ip_filter && ip_filter.strip.empty? + if !available? && !survey? + self.points_possible = current_points_possible end - self.title = t('#quizzes.quiz.default_title', "Unnamed Quiz") if self.title.blank? + self.title = t('#quizzes.quiz.default_title', "Unnamed Quiz") if title.blank? self.quiz_type ||= "assignment" - self.last_assignment_id = self.assignment_id_was if self.assignment_id_was - if (!graded? && self.assignment_id) || (self.assignment_id_was && self.assignment_id != self.assignment_id_was) - @old_assignment_id = self.assignment_id_was - @assignment_to_set = self.assignment + self.last_assignment_id = assignment_id_was if assignment_id_was + if (!graded? && assignment_id) || (assignment_id_was && assignment_id != assignment_id_was) + @old_assignment_id = assignment_id_was + @assignment_to_set = assignment self.assignment_id = nil end - unless self.require_lockdown_browser + unless require_lockdown_browser self.require_lockdown_browser_for_results = false end - self.assignment_group_id ||= self.assignment.assignment_group_id if self.assignment - self.question_count = self.question_count(true) - @update_existing_submissions = true if self.for_assignment? && self.quiz_type_changed? + self.assignment_group_id ||= assignment.assignment_group_id if assignment + self.question_count = question_count(true) + @update_existing_submissions = true if for_assignment? && quiz_type_changed? @stored_questions = nil [ @@ -167,7 +167,7 @@ def set_defaults # harder to mess up (like someone setting using workflow_state directly) def generate_quiz_data_on_publish if workflow_state == 'available' - self.generate_quiz_data + generate_quiz_data self.published_at = Time.zone.now end end @@ -206,16 +206,16 @@ def link_assignment_overrides def build_assignment(force: false) # There is no need to create a new assignment if the quiz being deleted - return if self.workflow_state == 'deleted' + return if workflow_state == 'deleted' - if !self.assignment_id && self.graded? && (force || ![:assignment, :clone, :migration].include?(@saved_by)) + if !assignment_id && graded? && (force || ![:assignment, :clone, :migration].include?(@saved_by)) assignment = self.assignment - assignment ||= self.context.assignments.build(:title => self.title, :due_at => self.due_at, :submission_types => 'online_quiz') + assignment ||= context.assignments.build(:title => title, :due_at => due_at, :submission_types => 'online_quiz') assignment.assignment_group_id = self.assignment_group_id - assignment.only_visible_to_overrides = self.only_visible_to_overrides + assignment.only_visible_to_overrides = only_visible_to_overrides assignment.saved_by = :quiz unless deleted? - assignment.workflow_state = self.published? ? 'published' : 'unpublished' + assignment.workflow_state = published? ? 'published' : 'unpublished' end assignment.save self.assignment_id = assignment.id @@ -223,7 +223,7 @@ def build_assignment(force: false) end def readable_type - self.survey? ? t('#quizzes.quiz.types.survey', "Survey") : t('#quizzes.quiz.types.quiz', "Quiz") + survey? ? t('#quizzes.quiz.types.survey', "Survey") : t('#quizzes.quiz.types.quiz', "Quiz") end def valid_ip?(ip) @@ -249,14 +249,14 @@ def self.count_points_possible(entries) end def current_points_possible - entries = self.root_entries - return self.assignment.points_possible if entries.empty? && self.assignment + entries = root_entries + return assignment.points_possible if entries.empty? && assignment self.class.count_points_possible(entries) end def set_unpublished_question_count - entries = self.root_entries(true) + entries = root_entries(true) cnt = 0 entries.each do |e| if e[:question_points] @@ -274,11 +274,11 @@ def set_unpublished_question_count end def for_assignment? - self.assignment_id && self.assignment && self.assignment.submission_types == 'online_quiz' + assignment_id && assignment && assignment.submission_types == 'online_quiz' end def muted? - self.assignment&.muted? + assignment&.muted? end alias_method :destroy_permanently!, :destroy @@ -286,30 +286,30 @@ def muted? def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - res = self.save! - if self.for_assignment? - self.assignment.destroy unless self.assignment.deleted? + res = save! + if for_assignment? + assignment.destroy unless assignment.deleted? end res end def restore(_from = nil) - self.workflow_state = if self.has_student_submissions? + self.workflow_state = if has_student_submissions? "available" else "unpublished" end - self.save - self.assignment.restore(:quiz) if self.for_assignment? + save + assignment.restore(:quiz) if for_assignment? end def unlink!(type) @saved_by = type self.assignment = nil - if self.root_entries.empty? && !self.available? - self.destroy + if root_entries.empty? && !available? + destroy else - self.save + save end end @@ -322,7 +322,7 @@ def lock_at=(val) val = val.in_time_zone.end_of_day if val.is_a?(Date) if val.is_a?(String) super(Time.zone.parse(val)) - self.lock_at = CanvasTime.fancy_midnight(self.lock_at) unless val.include?(':') + self.lock_at = CanvasTime.fancy_midnight(lock_at) unless val.include?(':') else super(val) end @@ -362,24 +362,24 @@ def graded_survey? end def ungraded? - !self.graded? + !graded? end # Determine if the quiz should display the correct answers and the score points. # Takes into account the quiz settings, the user viewing and the submission to # be viewed. def show_correct_answers?(user, submission) - show_at = self.show_correct_answers_at - hide_at = self.hide_correct_answers_at + show_at = show_correct_answers_at + hide_at = hide_correct_answers_at # NOTE: We don't have a submission user when the teacher is previewing the # quiz and displaying the results' - return true if self.grants_right?(user, :grade) && + return true if grants_right?(user, :grade) && (submission&.user && submission.user != user) - return false unless self.show_correct_answers + return false unless show_correct_answers - if self.show_correct_answers_last_attempt && submission + if show_correct_answers_last_attempt && submission return submission.attempts_left == 0 && submission.completed? end @@ -387,7 +387,7 @@ def show_correct_answers?(user, submission) # see their correct answers, don't take the showAt/hideAt dates into # consideration because we really want them to see the CAs just once, # no matter when they submit. - return true if self.one_time_results + return true if one_time_results # Are we past the date the correct answers should no longer be shown after? return false if hide_at.present? && Time.zone.now > hide_at @@ -396,7 +396,7 @@ def show_correct_answers?(user, submission) end def restrict_answers_for_concluded_course?(user: nil) - course = self.context + course = context return false unless course.root_account.settings[:restrict_quiz_questions] if user.present? @@ -411,7 +411,7 @@ def update_existing_submissions # If the quiz suddenly changes from non-graded to graded, # then this will update the existing submissions to reflect quiz # scores in the gradebook. - self.quiz_submissions.each(&:save!) + quiz_submissions.each(&:save!) end def update_learning_outcome_results(state) @@ -427,7 +427,7 @@ def restore_learning_outcome_results end def destroy_related_submissions - self.quiz_submissions.each do |qs| + quiz_submissions.each do |qs| submission = qs.submission qs.submission = nil qs.save! if qs.changed? @@ -438,43 +438,43 @@ def destroy_related_submissions attr_accessor :saved_by def update_assignment - delay_if_production.set_unpublished_question_count if self.id - if !self.assignment_id && @old_assignment_id - self.context_module_tags.preload(:context_module => :content_tags).each(&:confirm_valid_module_requirements) + delay_if_production.set_unpublished_question_count if id + if !assignment_id && @old_assignment_id + context_module_tags.preload(:context_module => :content_tags).each(&:confirm_valid_module_requirements) end - if !self.graded? && (@old_assignment_id || self.last_assignment_id) + if !graded? && (@old_assignment_id || last_assignment_id) ::Assignment.where( - id: [@old_assignment_id, self.last_assignment_id].compact, + id: [@old_assignment_id, last_assignment_id].compact, submission_types: 'online_quiz' ).update_all(:workflow_state => 'deleted', :updated_at => Time.now.utc) - self.course.recompute_student_scores + course.recompute_student_scores delay_if_production(priority: Delayed::HIGH_PRIORITY).destroy_related_submissions ::ContentTag.delete_for(::Assignment.find(@old_assignment_id)) if @old_assignment_id - ::ContentTag.delete_for(::Assignment.find(self.last_assignment_id)) if self.last_assignment_id + ::ContentTag.delete_for(::Assignment.find(last_assignment_id)) if last_assignment_id end delay_if_production.update_existing_submissions if @update_existing_submissions - if (self.assignment || @assignment_to_set) && (@assignment_id_set || self.for_assignment?) && @saved_by != :assignment - unless !self.graded? && @old_assignment_id - Quizzes::Quiz.where("assignment_id=? AND id<>?", self.assignment_id, self).update_all(:workflow_state => 'deleted', :assignment_id => nil, :updated_at => Time.now.utc) if self.assignment_id - self.assignment = @assignment_to_set if @assignment_to_set && !self.assignment - a = self.assignment + if (assignment || @assignment_to_set) && (@assignment_id_set || for_assignment?) && @saved_by != :assignment + unless !graded? && @old_assignment_id + Quizzes::Quiz.where("assignment_id=? AND id<>?", assignment_id, self).update_all(:workflow_state => 'deleted', :assignment_id => nil, :updated_at => Time.now.utc) if assignment_id + self.assignment = @assignment_to_set if @assignment_to_set && !assignment + a = assignment a.quiz&.clear_changes_information # AR#changes persist in after_saves now - needed to prevent an autosave loop - a.points_possible = self.points_possible - a.description = self.description - a.title = self.title - a.due_at = self.due_at - a.lock_at = self.lock_at - a.unlock_at = self.unlock_at - a.only_visible_to_overrides = self.only_visible_to_overrides + a.points_possible = points_possible + a.description = description + a.title = title + a.due_at = due_at + a.lock_at = lock_at + a.unlock_at = unlock_at + a.only_visible_to_overrides = only_visible_to_overrides a.submission_types = "online_quiz" a.assignment_group_id = self.assignment_group_id a.saved_by = :quiz - if self.saved_by == :migration + if saved_by == :migration a.needs_update_cached_due_dates = true if a.update_cached_due_dates? end unless deleted? - a.workflow_state = self.published? ? 'published' : 'unpublished' + a.workflow_state = published? ? 'published' : 'unpublished' end @notify_of_update = a.will_save_change_to_workflow_state? && a.published? unless defined?(@notify_of_update) a.notify_of_update = @notify_of_update @@ -497,9 +497,9 @@ def check_if_needs_availability_cache_clear end def clear_availability_cache - if self.should_clear_availability_cache && !self.saved_by == :migration - self.clear_cache_key(:availability) - self.assignment&.clear_cache_key(:availability) + if should_clear_availability_cache && !saved_by == :migration + clear_cache_key(:availability) + assignment&.clear_cache_key(:availability) end end @@ -541,13 +541,13 @@ def update_quiz_submission_end_at_times end def root_entries_max_position - question_max = self.quiz_questions.active.where(quiz_group_id: nil).maximum(:position) - group_max = self.quiz_groups.maximum(:position) + question_max = quiz_questions.active.where(quiz_group_id: nil).maximum(:position) + group_max = quiz_groups.maximum(:position) [question_max, group_max, 0].compact.max end def active_quiz_questions_without_group - if self.quiz_questions.loaded? + if quiz_questions.loaded? active_quiz_questions.reject(&:quiz_group_id) else active_quiz_questions.where(quiz_group_id: nil).to_a @@ -555,7 +555,7 @@ def active_quiz_questions_without_group end def active_quiz_questions - if self.quiz_questions.loaded? + if quiz_questions.loaded? quiz_questions.select(&:active?) else quiz_questions.active @@ -569,8 +569,8 @@ def root_entries(force_check = false) return @root_entries if @root_entries && !force_check result = [] - result.concat self.active_quiz_questions_without_group - result.concat self.quiz_groups + result.concat active_quiz_questions_without_group + result.concat quiz_groups result = result.sort_by { |e| e.position || ::CanvasSort::Last }.map do |e| res = nil if e.is_a? Quizzes::QuizQuestion @@ -599,7 +599,7 @@ def question_count(force_check = false) return read_attribute(:question_count) if !force_check && read_attribute(:question_count) question_count = 0 - self.stored_questions.each do |q| + stored_questions.each do |q| if q[:pick_count] question_count += q[:pick_count] else @@ -648,13 +648,13 @@ def stored_questions(preview = false) @stored_questions = begin data_set = if preview - self.generate_quiz_data(:persist => false) + generate_quiz_data(:persist => false) else - self.quiz_data || [] + quiz_data || [] end builder = Quizzes::QuizQuestionBuilder.new({ - shuffle_answers: self.shuffle_answers + shuffle_answers: shuffle_answers }) builder.shuffle_quiz_data!(data_set) @@ -662,11 +662,11 @@ def stored_questions(preview = false) end def single_attempt? - self.allowed_attempts == 1 + allowed_attempts == 1 end def unlimited_attempts? - self.allowed_attempts == -1 + allowed_attempts == -1 end def build_submission_end_at(submission, with_time_limit = true) @@ -674,8 +674,8 @@ def build_submission_end_at(submission, with_time_limit = true) user = submission.user end_at = nil - if self.time_limit && with_time_limit - end_at = submission.started_at + (self.time_limit.to_f * 60.0) + if time_limit && with_time_limit + end_at = submission.started_at + (time_limit.to_f * 60.0) end # add extra time @@ -684,7 +684,7 @@ def build_submission_end_at(submission, with_time_limit = true) end # Admins can take the full quiz whenever they want - return end_at if user.is_a?(::User) && self.grants_right?(user, :grade) + return end_at if user.is_a?(::User) && grants_right?(user, :grade) # We no longer use enrollment_term but get this info from enrollment_state fallback_end_at = course.enrollments.for_user(user).active_by_date @@ -709,7 +709,7 @@ def generate_submission(user, preview = false) transaction do builder = Quizzes::QuizQuestionBuilder.new({ - shuffle_answers: self.shuffle_answers + shuffle_answers: shuffle_answers }) submission = Quizzes::SubmissionManager.new(self).find_or_create_submission(user, preview) @@ -720,10 +720,10 @@ def generate_submission(user, preview = false) submission.quiz_data = begin @stored_questions = nil - builder.build_submission_questions(self.id, self.stored_questions(preview)) + builder.build_submission_questions(id, stored_questions(preview)) end - submission.quiz_version = self.version_number + submission.quiz_version = version_number submission.started_at = ::Time.now submission.score_before_regrade = nil submission.end_at = build_submission_end_at(submission) @@ -758,7 +758,7 @@ def generate_submission_for_participant(quiz_participant) # the database and uses them to populate a static version that will # be held in Quizzes::Quiz.quiz_data def generate_quiz_data(opts = {}) - entries = self.root_entries(true) + entries = root_entries(true) t = Time.now entries.each do |e| e[:published_at] = t @@ -767,7 +767,7 @@ def generate_quiz_data(opts = {}) if opts[:persist] != false self.quiz_data = data - unless self.survey? + unless survey? possible = self.class.count_points_possible(data) self.points_possible = [possible, 0].max end @@ -779,8 +779,8 @@ def generate_quiz_data(opts = {}) def add_assessment_questions(assessment_questions, group = nil) questions = assessment_questions.map do |assessment_question| - question = self.quiz_questions.build - question.quiz_group_id = group.id if group && group.quiz_id == self.id + question = quiz_questions.build + question.quiz_group_id = group.id if group && group.quiz_id == id question.write_attribute(:question_data, assessment_question.question_data) question.assessment_question = assessment_question question.assessment_question_version = assessment_question.version_number @@ -791,9 +791,9 @@ def add_assessment_questions(assessment_questions, group = nil) end def quiz_title - result = self.title + result = title result = t('#quizzes.quiz.default_title', "Unnamed Quiz") if result == "undefined" || !result - result = self.assignment.title if self.assignment + result = assignment.title if assignment result end @@ -804,7 +804,7 @@ def low_level_locked_for?(user, opts = {}) user_submission = user && quiz_submissions.where(user_id: user.id).first return false if user_submission&.manually_unlocked - quiz_for_user = self.overridden_for(user) + quiz_for_user = overridden_for(user) unlock_time_not_yet_reached = quiz_for_user.unlock_at && quiz_for_user.unlock_at > Time.zone.now lock_time_already_occurred = quiz_for_user.lock_at && quiz_for_user.lock_at <= Time.zone.now @@ -834,9 +834,9 @@ def locked_by_assignment?(user, opts = {}) end def context_module_action(user, action, points = nil) - tags_to_update = self.context_module_tags.to_a - if self.assignment - tags_to_update += self.assignment.context_module_tags + tags_to_update = context_module_tags.to_a + if assignment + tags_to_update += assignment.context_module_tags end tags_to_update.each { |tag| tag.context_module_action(user, action, points) } end @@ -847,7 +847,7 @@ def locked=(new_val) if new_val # lock the quiz either until unlock_at, or indefinitely if unlock_at.nil? self.lock_at = Time.now - self.unlock_at = [self.lock_at, self.unlock_at].min if self.unlock_at + self.unlock_at = [lock_at, unlock_at].min if unlock_at else # unlock the quiz self.unlock_at = Time.now @@ -855,8 +855,8 @@ def locked=(new_val) end def locked? - (self.unlock_at && self.unlock_at > Time.now) || - (self.lock_at && self.lock_at <= Time.now) + (unlock_at && unlock_at > Time.now) || + (lock_at && lock_at <= Time.now) end def hide_results=(val) @@ -877,20 +877,20 @@ def hide_results=(val) def check_if_submissions_need_review self.class.connection.after_transaction_commit do - version_num = self.version_number + version_num = version_number submissions_to_update = [] - self.quiz_submissions.each do |sub| + quiz_submissions.each do |sub| next unless sub.completed? next if sub.quiz_version && sub.quiz_version >= version_num - if self.changed_significantly_since?(sub.quiz_version) + if changed_significantly_since?(sub.quiz_version) submissions_to_update << sub end end if submissions_to_update.any? - self.shard.activate do + shard.activate do Quizzes::QuizSubmission.where(:id => submissions_to_update).update_all(:workflow_state => 'pending_review', :updated_at => Time.now.utc) end end @@ -901,15 +901,15 @@ def changed_significantly_since?(version_number) @significant_version ||= {} return @significant_version[version_number] if @significant_version.key?(version_number) - old_version = self.versions.get(version_number).model + old_version = versions.get(version_number).model needs_review = false # Allow for floating point rounding error comparing to versions created before BigDecimal was used - needs_review = true if [old_version.points_possible, self.points_possible].count(&:present?) == 1 || - ((old_version.points_possible || 0) - (self.points_possible || 0)).abs > 0.0001 - needs_review = true if (old_version.quiz_data || []).length != (self.quiz_data || []).length + needs_review = true if [old_version.points_possible, points_possible].count(&:present?) == 1 || + ((old_version.points_possible || 0) - (points_possible || 0)).abs > 0.0001 + needs_review = true if (old_version.quiz_data || []).length != (quiz_data || []).length unless needs_review - new_data = self.quiz_data + new_data = quiz_data old_data = old_version.quiz_data new_data.each_with_index do |q, i| needs_review = true if (q[:id] || q['id']) != (old_data[i][:id] || old_data[i]['id']) @@ -931,20 +931,20 @@ def valid_quiz_type_values end def validate_ip_filter - return if self.ip_filter.blank? + return if ip_filter.blank? require 'ipaddr' begin - self.ip_filter.split(",").each { |filter| ::IPAddr.new(filter) } + ip_filter.split(",").each { |filter| ::IPAddr.new(filter) } rescue errors.add(:invalid_ip_filter, t('#quizzes.quiz.errors.invalid_ip_filter', "IP filter is not valid")) end end def validate_hide_results - return if self.hide_results.blank? + return if hide_results.blank? - unless valid_hide_results_values.include?(self.hide_results) + unless valid_hide_results_values.include?(hide_results) errors.add(:invalid_hide_results, t('#quizzes.quiz.errors.invalid_hide_results', "Hide results is not valid")) end end @@ -954,8 +954,8 @@ def valid_hide_results_values end def validate_correct_answer_visibility - show_at = self.show_correct_answers_at - hide_at = self.hide_correct_answers_at + show_at = show_correct_answers_at + hide_at = hide_correct_answers_at if show_at.present? && hide_at.present? && hide_at <= show_at errors.add(:show_correct_answers, 'bad_range') @@ -1041,11 +1041,11 @@ def post_to_sis? end def unpublished_changes? - self.last_edited_at && self.published_at && self.last_edited_at > self.published_at + last_edited_at && published_at && last_edited_at > published_at end def has_student_submissions? - self.quiz_submissions.not_settings_only.where.not(user_id: nil).exists? + quiz_submissions.not_settings_only.where.not(user_id: nil).exists? end # clear out all questions so that the quiz can be replaced. this is currently @@ -1056,8 +1056,8 @@ def clear_for_replacement return false if has_student_submissions? self.question_count = 0 - self.quiz_questions.active.map(&:destroy) - self.quiz_groups.destroy_all + quiz_questions.active.map(&:destroy) + quiz_groups.destroy_all self.quiz_data = nil true end @@ -1074,43 +1074,43 @@ def self.serialization_excludes set_policy do given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments) + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments) end can :manage and can :read and can :create and can :update and can :submit and can :preview given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_add) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_add) end can :read and can :create given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_edit) + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_edit) end can :manage and can :read and can :update and can :submit and can :preview given do |user, session| - !self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments) && - (self.context.account_membership_allows(user) || + !context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments) && + (context.account_membership_allows(user) || !due_for_any_student_in_closed_grading_period?) end can :delete given do |user, session| - self.context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && - self.context.grants_right?(user, session, :manage_assignments_delete) && - (self.context.account_membership_allows(user) || + context.root_account.feature_enabled?(:granular_permissions_manage_assignments) && + context.grants_right?(user, session, :manage_assignments_delete) && + (context.account_membership_allows(user) || !due_for_any_student_in_closed_grading_period?) end can :delete - given { |user, session| self.context.grants_right?(user, session, :manage_grades) } # admins.include? user } + given { |user, session| context.grants_right?(user, session, :manage_grades) } # admins.include? user } can :read_statistics and can :read and can :submit and can :grade and can :review_grades - given { |user| self.available? && self.context.try_rescue(:is_public) && !self.graded? && self.visible_to_user?(user) } + given { |user| available? && context.try_rescue(:is_public) && !graded? && visible_to_user?(user) } can :submit given { |user, session| context.grants_right?(user, session, :read_as_admin) } @@ -1121,7 +1121,7 @@ def self.serialization_excludes end can :read - given { |user, session| self.context.grants_right?(user, session, :view_all_grades) } + given { |user, session| context.grants_right?(user, session, :view_all_grades) } can :read_statistics and can :review_grades given do |user, session| @@ -1257,7 +1257,7 @@ def require_lockdown_browser alias_method :require_lockdown_browser?, :require_lockdown_browser def require_lockdown_browser_for_results - self.require_lockdown_browser && + require_lockdown_browser && self[:require_lockdown_browser_for_results] && Quizzes::Quiz.lockdown_browser_plugin_enabled? end @@ -1283,11 +1283,11 @@ def self.shuffleable_question_type?(question_type) end def shuffle_answers_for_user?(user) - self.shuffle_answers? && !self.grants_right?(user, :manage) + shuffle_answers? && !grants_right?(user, :manage) end def timer_autosubmit_disabled? - self.context&.root_account&.feature_enabled?(:timer_without_autosubmission) && self.disable_timer_autosubmission + context&.root_account&.feature_enabled?(:timer_without_autosubmission) && disable_timer_autosubmission end def access_code_key_for_user(user) @@ -1360,7 +1360,7 @@ def self.mark_quiz_edited(id) end def mark_edited! - self.class.mark_quiz_edited(self.id) + self.class.mark_quiz_edited(id) end def anonymous_survey? @@ -1374,7 +1374,7 @@ def has_file_upload_question? end def draft_state - state = self.workflow_state + state = workflow_state (state == 'available') ? 'active' : state end @@ -1393,10 +1393,10 @@ def regrade_if_published unless unpublished_changes? options = { quiz: self, - version_number: self.version_number + version_number: version_number } if current_quiz_question_regrades.present? - Quizzes::QuizRegrader::Regrader.delay(strand: "quiz:#{self.global_id}:regrading") + Quizzes::QuizRegrader::Regrader.delay(strand: "quiz:#{global_id}:regrading") .regrade!(options) end end @@ -1433,13 +1433,13 @@ def excused_for_student?(student) end def due_for_any_student_in_closed_grading_period?(periods = nil) - return false unless self.due_at || self.has_overrides? + return false unless due_at || has_overrides? - periods ||= GradingPeriod.for(self.course) + periods ||= GradingPeriod.for(course) due_in_closed_period = - !self.only_visible_to_overrides && - GradingPeriodHelper.date_in_closed_grading_period?(self.due_at, periods) - due_in_closed_period ||= self.active_assignment_overrides.any? do |override| + !only_visible_to_overrides && + GradingPeriodHelper.date_in_closed_grading_period?(due_at, periods) + due_in_closed_period ||= active_assignment_overrides.any? do |override| GradingPeriodHelper.date_in_closed_grading_period?(override.due_at, periods) end @@ -1460,13 +1460,13 @@ def due_for_any_student_in_closed_grading_period?(periods = nil) # def available_ip_filters filters = [] - accounts = self.context.account.account_chain.uniq + accounts = context.account.account_chain.uniq - if self.ip_filter.present? + if ip_filter.present? filters << { name: t('#quizzes.quiz.current_filter', 'Current Filter'), - account: self.title, - filter: self.ip_filter + account: title, + filter: ip_filter } end @@ -1497,18 +1497,18 @@ def self.reflection_type_name end def run_if_overrides_changed! - self.relock_modules! - self.clear_cache_key(:availability) - if self.assignment - self.assignment.clear_cache_key(:availability) - self.assignment.relock_modules! + relock_modules! + clear_cache_key(:availability) + if assignment + assignment.clear_cache_key(:availability) + assignment.relock_modules! end end # Assignment#run_if_overrides_changed_later! uses its keyword arguments, but # this method does not def run_if_overrides_changed_later!(**) - delay_if_production(singleton: "quiz_overrides_changed_#{self.global_id}").run_if_overrides_changed! + delay_if_production(singleton: "quiz_overrides_changed_#{global_id}").run_if_overrides_changed! end # returns visible students for differentiated assignments diff --git a/app/models/quizzes/quiz_extension.rb b/app/models/quizzes/quiz_extension.rb index 93a0bdc78dd4d..f03404edd6447 100644 --- a/app/models/quizzes/quiz_extension.rb +++ b/app/models/quizzes/quiz_extension.rb @@ -45,7 +45,7 @@ def self.build_extensions(students, quizzes, ext_params) ext_params.map do |params| student = students.find(params[:user_id]) submission = sub_manager.find_or_create_submission(student, nil, 'settings_only') - extension = self.new(submission, params) + extension = new(submission, params) yield extension if block_given? # use yielded block to check permissions extensions << extension end diff --git a/app/models/quizzes/quiz_group.rb b/app/models/quizzes/quiz_group.rb index 2dc843b93ca9f..1e5ea3f6ef64c 100644 --- a/app/models/quizzes/quiz_group.rb +++ b/app/models/quizzes/quiz_group.rb @@ -45,14 +45,14 @@ class Quizzes::QuizGroup < ActiveRecord::Base restrict_columns :content, [:name, :pick_count] def actual_pick_count - count = if self.assessment_question_bank + count = if assessment_question_bank # don't do a valid question check because we don't want to instantiate all the bank's questions - self.assessment_question_bank.assessment_question_count + assessment_question_bank.assessment_question_count else - self.quiz_questions.active.count + quiz_questions.active.count end - [self.pick_count.to_i, count].min + [pick_count.to_i, count].min end # QuizGroup.data is used when creating and editing a quiz, but @@ -62,12 +62,12 @@ def actual_pick_count # the quiz, as students see it. def data { - "id" => self.id, - "name" => self.name, - "pick_count" => self.pick_count, - "question_points" => self.question_points, - "questions" => self.assessment_question_bank_id ? [] : self.quiz_questions.active.map(&:data), - "assessment_question_bank_id" => self.assessment_question_bank_id + "id" => id, + "name" => name, + "pick_count" => pick_count, + "question_points" => question_points, + "questions" => assessment_question_bank_id ? [] : quiz_questions.active.map(&:data), + "assessment_question_bank_id" => assessment_question_bank_id }.with_indifferent_access end @@ -84,12 +84,12 @@ def self.update_all_positions!(groups) private def update_quiz - Quizzes::Quiz.mark_quiz_edited(self.quiz_id) + Quizzes::Quiz.mark_quiz_edited(quiz_id) end def infer_position - if !self.position && self.quiz - self.position = self.quiz.root_entries_max_position + 1 + if !position && quiz + self.position = quiz.root_entries_max_position + 1 end end diff --git a/app/models/quizzes/quiz_participant.rb b/app/models/quizzes/quiz_participant.rb index 315b82a3faf3c..c761c1f78537b 100644 --- a/app/models/quizzes/quiz_participant.rb +++ b/app/models/quizzes/quiz_participant.rb @@ -59,6 +59,6 @@ def initialize(user, user_code, access_code = nil, ip_address = nil, token = nil # Note that this does not actually take the Quiz's public-participation status # into account, only the fact that the participant is authentic or not. def anonymous? - self.user.nil? && self.user_code.present? + user.nil? && user_code.present? end end diff --git a/app/models/quizzes/quiz_question.rb b/app/models/quizzes/quiz_question.rb index 0f57492cf199e..3a54c74363596 100644 --- a/app/models/quizzes/quiz_question.rb +++ b/app/models/quizzes/quiz_question.rb @@ -72,11 +72,11 @@ class Quizzes::QuizQuestion < ActiveRecord::Base scope :not_deleted, -> { where.not(workflow_state: 'deleted').or(where(workflow_state: nil)) } def infer_defaults - if !self.position && self.quiz - self.position = if self.quiz_group - (self.quiz_group.quiz_questions.active.filter_map(&:position).max || 0) + 1 + if !position && quiz + self.position = if quiz_group + (quiz_group.quiz_questions.active.filter_map(&:position).max || 0) + 1 else - self.quiz.root_entries_max_position + 1 + quiz.root_entries_max_position + 1 end end end @@ -84,7 +84,7 @@ def infer_defaults protected :infer_defaults def update_quiz - Quizzes::Quiz.mark_quiz_edited(self.quiz_id) + Quizzes::Quiz.mark_quiz_edited(quiz_id) end # @param [Hash] data @@ -112,9 +112,9 @@ def question_data=(in_data) update_question_regrade(data[:regrade_option], data[:regrade_user]) end - return if data == self.question_data + return if data == question_data - data = AssessmentQuestion.parse_question(data, self.assessment_question) + data = AssessmentQuestion.parse_question(data, assessment_question) data[:name] = data[:question_name] write_attribute(:question_data, data.to_hash) @@ -130,8 +130,8 @@ def question_data data = Quizzes::QuizQuestion::QuestionData.new(data || HashWithIndifferentAccess.new) end - unless data[:id].present? && !self.id - data[:id] = self.id + unless data[:id].present? && !id + data[:id] = id end data @@ -143,19 +143,19 @@ def assessment_question=(aq) end def delete_assessment_question - if self.assessment_question&.editable_by?(self) - self.assessment_question.destroy + if assessment_question&.editable_by?(self) + assessment_question.destroy end end def create_assessment_question - return if self.question_data&.is_type?(:text_only) + return if question_data&.is_type?(:text_only) - aq = self.assessment_question || AssessmentQuestion.new + aq = assessment_question || AssessmentQuestion.new if aq.editable_by?(self) - aq.question_data = self.question_data - aq.initial_context = self.quiz.context if self.quiz&.context + aq.question_data = question_data + aq.initial_context = quiz.context if quiz&.context aq.save! if aq.new_record? end @@ -167,7 +167,7 @@ def create_assessment_question def update_assessment_question!(aq, quiz_group_id, duplicate_index) if assessment_question_version.blank? || assessment_question_version < aq.version_number self.assessment_question = aq - self.write_attribute(:question_data, aq.question_data) + write_attribute(:question_data, aq.question_data) end self.quiz_group_id = quiz_group_id self.duplicate_index = duplicate_index @@ -177,21 +177,21 @@ def update_assessment_question!(aq, quiz_group_id, duplicate_index) end def validate_blank_questions - return if self.question_data && !(self.question_data.is_type?(:fill_in_multiple_blanks) || self.question_data.is_type?(:short_answer)) + return if question_data && !(question_data.is_type?(:fill_in_multiple_blanks) || question_data.is_type?(:short_answer)) - qd = self.question_data + qd = question_data qd.answers = qd.answers.reject { |answer| answer['text'].empty? } self.question_data = qd - self.question_data_will_change! + question_data_will_change! true end def clone_for(quiz, dup = nil, **) dup ||= Quizzes::QuizQuestion.new - self.attributes.except("id", "quiz_id", "quiz_group_id", "question_data").each do |key, val| + attributes.except("id", "quiz_id", "quiz_group_id", "question_data").each do |key, val| dup.send("#{key}=", val) end - data = self.question_data || HashWithIndifferentAccess.new + data = question_data || HashWithIndifferentAccess.new data.delete(:id) # if options[:old_context] && options[:new_context] # data = Quizzes::QuizQuestion.migrate_question_hash(data, options) @@ -207,10 +207,10 @@ def clone_for(quiz, dup = nil, **) # be futzing with questions and groups and not affect # the quiz, as students see it. def data - res = (self.question_data || self.assessment_question.question_data) rescue Quizzes::QuizQuestion::QuestionData.new(HashWithIndifferentAccess.new) - res[:assessment_question_id] = self.assessment_question_id + res = (question_data || assessment_question.question_data) rescue Quizzes::QuizQuestion::QuestionData.new(HashWithIndifferentAccess.new) + res[:assessment_question_id] = assessment_question_id res[:question_name] = t('#quizzes.quiz_question.defaults.question_name', "Question") if res[:question_name].blank? - res[:id] = self.id + res[:id] = id res.to_hash end @@ -233,7 +233,7 @@ def self.update_all_positions!(questions, quiz_group = nil) def destroy self.workflow_state = 'deleted' - self.save + save end private diff --git a/app/models/quizzes/quiz_question/answer_serializers/answer_serializer.rb b/app/models/quizzes/quiz_question/answer_serializers/answer_serializer.rb index ecd532fe201a8..14c5b64ac3360 100644 --- a/app/models/quizzes/quiz_question/answer_serializers/answer_serializer.rb +++ b/app/models/quizzes/quiz_question/answer_serializers/answer_serializer.rb @@ -53,7 +53,7 @@ def deserialize(submission_data, full: false) end def self.question_type - self.name.demodulize.underscore + name.demodulize.underscore end # Prevent the serializer from locating which question data to use for doing @@ -74,7 +74,7 @@ def override_question_data(question_data) # # This varies between question types, so some serializers will override this. def question_key - @question_key ||= ['question', self.question.id].join('_') + @question_key ||= ['question', question.id].join('_') end # Locate the question data that is usable by *students* when they take the @@ -93,8 +93,8 @@ def question_key # @return [Hash] The question data. def frozen_question_data @frozen_question_data ||= begin - question_id = self.question.id - quiz = self.question.quiz + question_id = question.id + quiz = question.quiz quiz_data = quiz.quiz_data || quiz.stored_questions quiz_data.detect { |question| question[:id].to_i == question_id } || self.question.question_data diff --git a/app/models/quizzes/quiz_question/base.rb b/app/models/quizzes/quiz_question/base.rb index 7d012616e08a5..1816346799f33 100644 --- a/app/models/quizzes/quiz_question/base.rb +++ b/app/models/quizzes/quiz_question/base.rb @@ -44,7 +44,7 @@ def self.inherited(klass) # override to change the name of the question type, defaults to the underscore-ized class name def self.question_type - self.name.demodulize.underscore + name.demodulize.underscore end def initialize(question_data) @@ -118,7 +118,7 @@ def requires_manual_scoring?(_user_answer) end def score_question(answer_data, user_answer = nil) - user_answer ||= Quizzes::QuizQuestion::UserAnswer.new(self.question_id, self.points_possible, answer_data) + user_answer ||= Quizzes::QuizQuestion::UserAnswer.new(question_id, points_possible, answer_data) user_answer.total_parts = total_answer_parts correct_parts = correct_answer_parts(user_answer) if !correct_parts.nil? diff --git a/app/models/quizzes/quiz_question/file_upload_question.rb b/app/models/quizzes/quiz_question/file_upload_question.rb index b1094f761652f..bee8d5aa3cbae 100644 --- a/app/models/quizzes/quiz_question/file_upload_question.rb +++ b/app/models/quizzes/quiz_question/file_upload_question.rb @@ -39,8 +39,8 @@ def stats(responses) end def score_question(answer_data) - user_answer = Quizzes::QuizQuestion::FileUploadAnswer.new(self.question_id, - self.points_possible, + user_answer = Quizzes::QuizQuestion::FileUploadAnswer.new(question_id, + points_possible, answer_data) super(answer_data, user_answer) end diff --git a/app/models/quizzes/quiz_statistics.rb b/app/models/quizzes/quiz_statistics.rb index 778864542c91d..d4912e6cc91a0 100644 --- a/app/models/quizzes/quiz_statistics.rb +++ b/app/models/quizzes/quiz_statistics.rb @@ -114,10 +114,10 @@ def csv_generation_failed? end def abort_csv_generation - self.progress.destroy - self.reload + progress.destroy + reload - Delayed::Job.where({ strand: self.csv_job_strand_id }).destroy_all + Delayed::Job.where({ strand: csv_job_strand_id }).destroy_all end def self.csv_job_tag @@ -125,7 +125,7 @@ def self.csv_job_tag end def csv_job_strand_id - Shard.birth.activate { "quiz_statistics_#{quiz_id}_#{self.id}" } + Shard.birth.activate { "quiz_statistics_#{quiz_id}_#{id}" } end def update_progress(i, n) diff --git a/app/models/quizzes/quiz_statistics/item_analysis.rb b/app/models/quizzes/quiz_statistics/item_analysis.rb index 3f95793422aaa..eea1e55437855 100644 --- a/app/models/quizzes/quiz_statistics/item_analysis.rb +++ b/app/models/quizzes/quiz_statistics/item_analysis.rb @@ -22,7 +22,7 @@ class Quizzes::QuizStatistics::ItemAnalysis < Quizzes::QuizStatistics::Report def generatable? - !self.quiz.survey? + !quiz.survey? end def readable_type diff --git a/app/models/quizzes/quiz_submission.rb b/app/models/quizzes/quiz_submission.rb index d3afb79de93d7..21f2a1706fb4c 100644 --- a/app/models/quizzes/quiz_submission.rb +++ b/app/models/quizzes/quiz_submission.rb @@ -75,8 +75,8 @@ def grade_submission! after_update :update_planner_override def update_planner_override - return unless self.saved_change_to_workflow_state? - return unless self.workflow_state == "complete" + return unless saved_change_to_workflow_state? + return unless workflow_state == "complete" PlannerHelper.complete_planner_override_for_quiz_submission(self) end @@ -109,25 +109,25 @@ def unenrolled_user_can_read?(user, session) end set_policy do - given { |user| user && user.id == self.user_id } + given { |user| user && user.id == user_id } can :read # allow anonymous users take ungraded quizzes from a public course given { |user, session| unenrolled_user_can_read?(user, session) } can :record_events - given { |user| user && user.id == self.user_id && end_date_is_valid? } + given { |user| user && user.id == user_id && end_date_is_valid? } can :record_events - given { |user| user && user.id == self.user_id && self.untaken? } + given { |user| user && user.id == user_id && untaken? } can :update - given { |user, session| self.quiz.grants_right?(user, session, :review_grades) } + given { |user, session| quiz.grants_right?(user, session, :review_grades) } can :read given { |user| user && - self.quiz.context.observer_enrollments.where(user_id: user, associated_user_id: self.user_id, workflow_state: 'active').exists? + quiz.context.observer_enrollments.where(user_id: user, associated_user_id: user_id, workflow_state: 'active').exists? } can :read @@ -165,10 +165,10 @@ def has_question?(id) end def temporary_data - raise "Cannot view temporary data for completed quiz" if self.completed? + raise "Cannot view temporary data for completed quiz" if completed? raise "Cannot view temporary data for completed quiz" if graded? - (self.submission_data || {}).with_indifferent_access + (submission_data || {}).with_indifferent_access end def question_answered?(id) @@ -186,10 +186,10 @@ def question_answered?(id) end def data - raise "Cannot view data for uncompleted quiz" unless self.completed? + raise "Cannot view data for uncompleted quiz" unless completed? raise "Cannot view data for uncompleted quiz" unless graded? - Utf8Cleaner.recursively_strip_invalid_utf8!(self.submission_data, true) + Utf8Cleaner.recursively_strip_invalid_utf8!(submission_data, true) end def results_visible?(user: nil) @@ -238,16 +238,16 @@ def self.needs_grading # There is also a needs_grading scope which needs to replicate this logic def needs_grading?(strict = false) - overdue_and_needs_submission?(strict) || (self.completed? && !graded?) + overdue_and_needs_submission?(strict) || (completed? && !graded?) end def overdue_and_needs_submission?(strict = false) - return true if strict && self.untaken? && self.overdue?(true) + return true if strict && untaken? && overdue?(true) - if self.untaken? && self.end_at && self.end_at < Time.zone.now - return true unless self.quiz&.timer_autosubmit_disabled? + if untaken? && end_at && end_at < Time.zone.now + return true unless quiz&.timer_autosubmit_disabled? - self.end_at_without_time_limit && self.end_at_without_time_limit < Time.zone.now + end_at_without_time_limit && end_at_without_time_limit < Time.zone.now else false end @@ -255,7 +255,7 @@ def overdue_and_needs_submission?(strict = false) alias_method :overdue_and_needs_submission, :overdue_and_needs_submission? def end_date_needs_recalculated? - self.end_at.nil? && !!quiz.time_limit + end_at.nil? && !!quiz.time_limit end def end_date_is_valid? @@ -263,7 +263,7 @@ def end_date_is_valid? end def has_seen_results? - !!self.has_seen_results + !!has_seen_results end def finished_in_words @@ -272,15 +272,15 @@ def finished_in_words end def finished_at_fallback - [self.end_at, Time.zone.now].compact.min + [end_at, Time.zone.now].compact.min end def points_possible_at_submission_time - self.questions.filter_map { |q| q[:points_possible].to_f }.sum || 0 + questions.filter_map { |q| q[:points_possible].to_f }.sum || 0 end def questions - Utf8Cleaner.recursively_strip_invalid_utf8!(self.quiz_data, true) || [] + Utf8Cleaner.recursively_strip_invalid_utf8!(quiz_data, true) || [] end def backup_submission_data(params) @@ -288,13 +288,13 @@ def backup_submission_data(params) params = sanitize_params(params) - new_params = if !graded? && self.submission_data[:attempt] == self.attempt - self.submission_data.deep_merge(params) rescue params + new_params = if !graded? && submission_data[:attempt] == attempt + submission_data.deep_merge(params) rescue params else params end - new_params[:attempt] = self.attempt + new_params[:attempt] = attempt # take a snapshot every 5 other saves: new_params[:cnt] ||= 0 @@ -316,11 +316,11 @@ def record_answer(submission_data) end def record_creation_event - self.events.create!( + events.create!( event_type: Quizzes::QuizSubmissionEvent::EVT_SUBMISSION_CREATED, - event_data: { "quiz_version" => self.quiz_version, "quiz_data" => self.quiz_data }, + event_data: { "quiz_version" => quiz_version, "quiz_data" => quiz_data }, created_at: Time.zone.now, - attempt: self.attempt + attempt: attempt ) end @@ -365,13 +365,13 @@ def snapshot!(submission_data = {}, full_snapshot = false) snapshot_data = submission_data || {} if full_snapshot - snapshot_data = self.sanitize_params(snapshot_data).stringify_keys + snapshot_data = sanitize_params(snapshot_data).stringify_keys snapshot_data.merge!(self.submission_data || {}) end Quizzes::QuizSubmissionSnapshot.create({ quiz_submission: self, - attempt: self.attempt, + attempt: attempt, data: snapshot_data }) end @@ -385,7 +385,7 @@ def quiz_questions end def update_quiz_points_possible - self.quiz_points_possible = self.quiz && self.quiz.points_possible + self.quiz_points_possible = quiz && quiz.points_possible end # This callback attempts to handle a somewhat edge-case reported in CNVS-8463 @@ -404,20 +404,20 @@ def update_quiz_points_possible # # Of course, this is purely guess-work and is not bullet-proof. def rectify_finished_at_drift - if self.finished_at && self.end_at && self.finished_at > self.end_at - drift = self.finished_at - self.end_at + if finished_at && end_at && finished_at > end_at + drift = finished_at - end_at if drift <= GRACEFUL_FINISHED_AT_DRIFT_PERIOD.to_i - self.finished_at = self.end_at + self.finished_at = end_at end end end def update_kept_score - return if self.manually_scored || @skip_after_save_score_updates + return if manually_scored || @skip_after_save_score_updates - if self.completed? - if self.submission_data && !graded? + if completed? + if submission_data && !graded? Quizzes::SubmissionGrader.new(self).grade_submission end @@ -431,9 +431,9 @@ def update_kept_score # so we do not bother updating kept_score in previous versions when they are # updated. def score_to_keep - if self.quiz && self.quiz.scoring_policy == "keep_highest" + if quiz && quiz.scoring_policy == "keep_highest" highest_score_so_far - elsif self.quiz && self.quiz.scoring_policy == "keep_average" + elsif quiz && quiz.scoring_policy == "keep_average" average_score_so_far else # keep_latest latest_score @@ -441,21 +441,21 @@ def score_to_keep end def update_assignment_submission - return if self.manually_scored || @skip_after_save_score_updates + return if manually_scored || @skip_after_save_score_updates - if self.quiz&.for_assignment? && assignment && !self.submission && self.user_id - self.submission = assignment.find_or_create_submission(self.user_id) + if quiz&.for_assignment? && assignment && !submission && user_id + self.submission = assignment.find_or_create_submission(user_id) end - if self.completed? && self.submission - @assignment_submission = self.submission - @assignment_submission.score = self.kept_score if self.kept_score - @assignment_submission.submitted_at = self.finished_at + if completed? && submission + @assignment_submission = submission + @assignment_submission.score = kept_score if kept_score + @assignment_submission.submitted_at = finished_at @assignment_submission.grade_matches_current_submission = true - @assignment_submission.quiz_submission_id = self.id - @assignment_submission.graded_at = [self.end_at, Time.zone.now].compact.min - @assignment_submission.grader_id = self.grader_id || "-#{self.quiz_id}".to_i - @assignment_submission.body = "user: #{self.user_id}, quiz: #{self.quiz_id}, score: #{self.score}, time: #{Time.now}" - @assignment_submission.user_id = self.user_id + @assignment_submission.quiz_submission_id = id + @assignment_submission.graded_at = [end_at, Time.zone.now].compact.min + @assignment_submission.grader_id = grader_id || "-#{quiz_id}".to_i + @assignment_submission.body = "user: #{user_id}, quiz: #{quiz_id}, score: #{score}, time: #{Time.now}" + @assignment_submission.user_id = user_id @assignment_submission.submission_type = "online_quiz" @assignment_submission.saved_by = :quiz_submission @@ -472,7 +472,7 @@ def save_assignment_submission def scores_for_versions(exclude_version_id) versions = self.versions.reload.reject { |v| v.id == exclude_version_id } rescue [] scores = {} - scores[attempt] = self.score if self.score + scores[attempt] = score if score # only most recent version for each attempt - some have regraded a version versions.sort_by(&:number).reverse_each do |ver| @@ -499,7 +499,7 @@ def highest_score_so_far(exclude_version_id = nil) def latest_score # the current model's score is the latest, unless the quiz is currently in # progress, in which case it is nil - s = self.score + s = score # otherwise, try to be the latest version's score, if possible if s.nil? @@ -515,7 +515,7 @@ def latest_score # Adjust the fudge points so that the score is the given score # Used when the score is explicitly set by teacher instead of auto-calculating def set_final_score(final_score) - version = self.versions.current # this gets us the most recent completed version + version = versions.current # this gets us the most recent completed version return if final_score.blank? || version.blank? self.manually_scored = false @@ -530,12 +530,12 @@ def set_final_score(final_score) to_be_kept_score = final_score self.fudge_points = new_fudge - if self.workflow_state == "pending_review" + if workflow_state == "pending_review" self.workflow_state = "complete" self.has_seen_results = false end - if self.quiz && self.quiz.scoring_policy == "keep_highest" + if quiz && quiz.scoring_policy == "keep_highest" # exclude the score of the version we're curretly overwriting if to_be_kept_score < highest_score_so_far(version.id) self.manually_scored = true @@ -546,33 +546,33 @@ def set_final_score(final_score) # we might be in the middle of a new attempt, in which case we don't want # to overwrite the score and fudge points when we save - self.reload unless self.completed? + reload unless completed? self.kept_score = to_be_kept_score - self.without_versioning(&:save) + without_versioning(&:save) @skip_after_save_score_updates = false end def time_left(hard: false) return unless end_at - return (end_at - Time.zone.now).round unless hard && self.quiz&.timer_autosubmit_disabled? + return (end_at - Time.zone.now).round unless hard && quiz&.timer_autosubmit_disabled? return (end_at_without_time_limit - Time.zone.now).round if end_at_without_time_limit end def less_than_allotted_time? - self.started_at && self.end_at && self.quiz && self.quiz.time_limit && (self.end_at - self.started_at) < self.quiz.time_limit.minutes.to_i + started_at && end_at && quiz && quiz.time_limit && (end_at - started_at) < quiz.time_limit.minutes.to_i end def completed? - self.complete? || self.pending_review? + complete? || pending_review? end def overdue?(strict = false) now = (Time.zone.now - ((strict ? 1 : 5) * 60)) return false unless end_at && end_at.localtime < now - if self.quiz&.timer_autosubmit_disabled? - return false unless self.end_at_without_time_limit && self.end_at_without_time_limit.localtime < now + if quiz&.timer_autosubmit_disabled? + return false unless end_at_without_time_limit && end_at_without_time_limit.localtime < now end true @@ -624,9 +624,9 @@ def score_affected_by_regrade? end def attempts_left - return -1 if self.quiz.allowed_attempts < 0 + return -1 if quiz.allowed_attempts < 0 - [0, self.quiz.allowed_attempts - (self.attempt || 0) + (self.extra_attempts || 0)].max + [0, quiz.allowed_attempts - (attempt || 0) + (extra_attempts || 0)].max end def mark_completed @@ -648,14 +648,14 @@ def mark_completed # # @return [QuizSubmission] self def complete!(submission_data = {}) - self.snapshot!(submission_data, true) - self.mark_completed + snapshot!(submission_data, true) + mark_completed Quizzes::SubmissionGrader.new(self).grade_submission self end def graded? - self.submission_data.is_a?(Array) + submission_data.is_a?(Array) end # Updates a simply_versioned version instance in-place. We want @@ -664,52 +664,52 @@ def graded? # simply_versioned for making this possible! def update_submission_version(version, attrs) version_data = YAML.load(version.yaml) - version_data["submission_data"] = self.submission_data if attrs.include?(:submission_data) + version_data["submission_data"] = submission_data if attrs.include?(:submission_data) version_data["temporary_user_code"] = "was #{version_data['score']} until #{Time.now}" - version_data["score"] = self.score if attrs.include?(:score) - version_data["fudge_points"] = self.fudge_points if attrs.include?(:fudge_points) - version_data["workflow_state"] = self.workflow_state if attrs.include?(:workflow_state) - version_data["manually_scored"] = self.manually_scored if attrs.include?(:manually_scored) + version_data["score"] = score if attrs.include?(:score) + version_data["fudge_points"] = fudge_points if attrs.include?(:fudge_points) + version_data["workflow_state"] = workflow_state if attrs.include?(:workflow_state) + version_data["manually_scored"] = manually_scored if attrs.include?(:manually_scored) version.yaml = version_data.to_yaml version.save end def context_module_action self.class.connection.after_transaction_commit do - if self.quiz && self.user - if self.score - self.quiz.context_module_action(self.user, :scored, self.kept_score) + if quiz && user + if score + quiz.context_module_action(user, :scored, kept_score) end - if self.finished_at - self.quiz.context_module_action(self.user, :submitted, self.kept_score) # pass in the score so we don't accidentally unset a min_score requirement + if finished_at + quiz.context_module_action(user, :submitted, kept_score) # pass in the score so we don't accidentally unset a min_score requirement end end end end def update_scores(params) - original_score = self.score - original_workflow_state = self.workflow_state + original_score = score + original_workflow_state = workflow_state params = (params || {}).with_indifferent_access self.manually_scored = false self.grader_id = params[:grader_id] - self.submission&.mark_unread(self.user) + submission&.mark_unread(user) versions = self.versions version = versions.current version = versions.get(params[:submission_version_number]) if params[:submission_version_number] # note that self may not match versions.current, because we only save a new version on actual submit - raise "Can't update submission scores unless it's completed" if !self.completed? && !params[:submission_version_number] + raise "Can't update submission scores unless it's completed" if !completed? && !params[:submission_version_number] data = version.model.submission_data || [] res = [] tally = 0 - completed_before_changes = self.completed? + completed_before_changes = completed? self.workflow_state = "complete" self.fudge_points = params[:fudge_points].to_f if params[:fudge_points] && params[:fudge_points] != "" - tally += self.fudge_points if self.fudge_points + tally += fudge_points if fudge_points data.each do |answer| unless answer.respond_to?(:with_indifferent_access) - logger.error "submission = #{self.to_json}" + logger.error "submission = #{to_json}" logger.error "answer = #{answer.inspect}" raise "Quizzes::QuizSubmission.update_scores called on a quiz that appears to be in progress" end @@ -750,8 +750,8 @@ def update_scores(params) # first we update the version we've been modifying, so that all versions are current. update_submission_version(version, [:submission_data, :score, :fudge_points, :workflow_state]) - if version.model.attempt != self.attempt || !completed_before_changes - self.reload + if version.model.attempt != attempt || !completed_before_changes + reload # score_to_keep should work regardless of the current model workflow_state and score # (ie even if the current model is an in-progress submission) @@ -761,22 +761,22 @@ def update_scores(params) # will handle updating the submission. otherwise we need to set its score # here so that when it is touched by the association, it does not try to # sync an old score back to this quiz_submission - if !self.completed? && self.submission - s = self.submission - s.score = self.kept_score + if !completed? && submission + s = submission + s.score = kept_score s.grade_change_event_author_id = params[:grader_id] s.grade_matches_current_submission = true - s.body = "user: #{self.user_id}, quiz: #{self.quiz_id}, score: #{self.kept_score}, time: #{Time.now}" + s.body = "user: #{user_id}, quiz: #{quiz_id}, score: #{kept_score}, time: #{Time.now}" s.saved_by = :quiz_submission end end # submission has to be saved with versioning # to help Auditors::GradeChange record grade_before correctly - self.submission.with_versioning(explicit: true, &:save) if self.submission.present? - self.without_versioning(&:save) + submission.with_versioning(explicit: true, &:save) if submission.present? + without_versioning(&:save) - self.reload + reload grader = Quizzes::SubmissionGrader.new(self) if grader.outcomes_require_update(self, original_score, original_workflow_state) grader.track_outcomes(version.model.attempt) @@ -785,7 +785,7 @@ def update_scores(params) end def duration - (self.finished_at || self.started_at) - self.started_at rescue 0 + (finished_at || started_at) - started_at rescue 0 end def time_spent @@ -824,7 +824,7 @@ def course_broadcast_data # submissions, not quiz submissions. The necessary delegations # are at the bottom of this class. p.dispatch :submission_graded - p.to { ([user] + User.observing_students_in_course(user, self.context)).uniq(&:id) } + p.to { ([user] + User.observing_students_in_course(user, context)).uniq(&:id) } p.whenever { |q_sub| BroadcastPolicies::QuizSubmissionPolicy.new(q_sub) .should_dispatch_submission_graded? @@ -832,7 +832,7 @@ def course_broadcast_data p.data { course_broadcast_data } p.dispatch :submission_grade_changed - p.to { ([user] + User.observing_students_in_course(user, self.context)).uniq(&:id) } + p.to { ([user] + User.observing_students_in_course(user, context)).uniq(&:id) } p.whenever { |q_sub| BroadcastPolicies::QuizSubmissionPolicy.new(q_sub) .should_dispatch_submission_grade_changed? @@ -864,12 +864,12 @@ def delete_ignores end def valid_token?(token) - self.validation_token.blank? || self.validation_token == token + validation_token.blank? || validation_token == token end # TODO: this could probably be put in as a convenience method in simply_versioned def save_with_versioning! - self.with_versioning(true) { self.save! } + with_versioning(true) { save! } end # evizitei: these 3 delegations allow quiz submissions to be used in @@ -893,12 +893,12 @@ def save_with_versioning! # @return [Boolean] # Whether the QS is retriable. def retriable? - return true if self.preview? - return true if self.settings_only? + return true if preview? + return true if settings_only? attempts_left = self.attempts_left || 0 - self.completed? && (attempts_left > 0 || self.quiz.unlimited_attempts?) + completed? && (attempts_left > 0 || quiz.unlimited_attempts?) end # Locate the Quiz Submission for this participant, regardless of them being @@ -920,13 +920,13 @@ def ensure_question_reference_integrity! end def ensure_end_at_integrity! - if end_date_needs_recalculated? && !!self.started_at + if end_date_needs_recalculated? && !!started_at self.end_at = quiz.build_submission_end_at(self) - if self.untaken? - self.save! + if untaken? + save! else - self.with_versioning(true, &:save!) + with_versioning(true, &:save!) end end end diff --git a/app/models/quizzes/quiz_submission_event.rb b/app/models/quizzes/quiz_submission_event.rb index da9e9aed20204..ecde9e295ff10 100644 --- a/app/models/quizzes/quiz_submission_event.rb +++ b/app/models/quizzes/quiz_submission_event.rb @@ -47,9 +47,9 @@ class Quizzes::QuizSubmissionEvent < ActiveRecord::Base # # If this returns true, you can safely skip storing this event. def empty? - case self.event_type + case event_type when EVT_QUESTION_ANSWERED - self.answers.nil? || self.answers.empty? + answers.nil? || answers.empty? else false end diff --git a/app/models/report_snapshot.rb b/app/models/report_snapshot.rb index f6697c69706d8..b4dbf4176f9bb 100644 --- a/app/models/report_snapshot.rb +++ b/app/models/report_snapshot.rb @@ -51,9 +51,9 @@ def self.report_value_over_time(report, key) def report_value_over_time(*args) if args.length == 1 - ReportSnapshot.report_value_over_time(self.data, args.first) + ReportSnapshot.report_value_over_time(data, args.first) else - ReportSnapshot.report_value_over_time(self.data[args.first], args.last) + ReportSnapshot.report_value_over_time(data[args.first], args.last) end end @@ -81,8 +81,8 @@ def serialize_data scope :progressive, -> { where(:report_type => 'counts_progressive_detailed') } def push_to_instructure_if_collection_enabled - return if self.report_type != REPORT_TO_SEND - return if self.account != Account.default + return if report_type != REPORT_TO_SEND + return if account != Account.default collection_type = Setting.get("usage_statistics_collection", "opt_out") return if collection_type == "opt_out" @@ -92,7 +92,7 @@ def push_to_instructure_if_collection_enabled data = { "collection_type" => collection_type, "installation_uuid" => Canvas.installation_uuid, - "report_type" => self.report_type, + "report_type" => report_type, "data" => read_attribute(:data), "rails_env" => Rails.env } diff --git a/app/models/role.rb b/app/models/role.rb index ade8d59eae4bc..cdf9ad44698c3 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -37,8 +37,8 @@ module AssociationHelper def role return super if association(:role).loaded? - self.role = self.shard.activate do - Role.get_role_by_id(read_attribute(:role_id)) || (self.respond_to?(:default_role) ? self.default_role : nil) + self.role = shard.activate do + Role.get_role_by_id(read_attribute(:role_id)) || (respond_to?(:default_role) ? default_role : nil) end end @@ -47,8 +47,8 @@ def self.included(klass) end def resolve_cross_account_role - if self.will_save_change_to_role_id? && self.respond_to?(:root_account_id) && self.root_account_id && self.role.root_account_id != self.root_account_id - self.role = self.role.role_for_root_account_id(self.root_account_id) + if will_save_change_to_role_id? && respond_to?(:root_account_id) && root_account_id && role.root_account_id != root_account_id + self.role = role.role_for_root_account_id(root_account_id) end end end @@ -68,9 +68,9 @@ def resolve_cross_account_role validate :ensure_non_built_in_name def role_for_root_account_id(target_root_account_id) - if self.built_in? && - self.root_account_id != target_root_account_id && - (target_role = Role.get_built_in_role(self.name, root_account_id: target_root_account_id)) + if built_in? && + root_account_id != target_root_account_id && + (target_role = Role.get_built_in_role(name, root_account_id: target_root_account_id)) target_role else self @@ -78,28 +78,28 @@ def role_for_root_account_id(target_root_account_id) end def ensure_unique_name_for_account - if self.active? - scope = Role.where("name = ? AND account_id = ? AND workflow_state = ?", self.name, self.account_id, 'active') - if self.new_record? ? scope.exists? : scope.where.not(id: self.id).exists? - self.errors.add(:label, t(:duplicate_role, 'A role with this name already exists')) + if active? + scope = Role.where("name = ? AND account_id = ? AND workflow_state = ?", name, account_id, 'active') + if new_record? ? scope.exists? : scope.where.not(id: id).exists? + errors.add(:label, t(:duplicate_role, 'A role with this name already exists')) false end end end def ensure_non_built_in_name - if !self.built_in? && Role.built_in_roles(root_account_id: self.root_account_id).map(&:label).include?(self.name) - self.errors.add(:label, t(:duplicate_role, 'A role with this name already exists')) + if !built_in? && Role.built_in_roles(root_account_id: root_account_id).map(&:label).include?(name) + errors.add(:label, t(:duplicate_role, 'A role with this name already exists')) false end end def infer_root_account_id - unless self.account - self.errors.add(:account_id) + unless account + errors.add(:account_id) throw :abort end - self.root_account_id = self.account.resolved_root_account_id + self.root_account_id = account.resolved_root_account_id end include Workflow @@ -150,15 +150,15 @@ def self.get_built_in_role(name, root_account_id:) end def ==(other_role) - if other_role.is_a?(Role) && self.built_in? && other_role.built_in? - self.name == other_role.name # be equivalent even if they're on different shards/root_accounts + if other_role.is_a?(Role) && built_in? && other_role.built_in? + name == other_role.name # be equivalent even if they're on different shards/root_accounts else super end end def visible? - self.active? || (self.built_in? && !["AccountMembership", "NoPermissions"].include?(self.name)) + active? || (built_in? && !["AccountMembership", "NoPermissions"].include?(name)) end def account_role? @@ -170,25 +170,25 @@ def course_role? end def label - if self.built_in? - if self.course_role? - RoleOverride.enrollment_type_labels.detect { |label| label[:name] == self.name }[:label].call - elsif self.name == 'AccountAdmin' + if built_in? + if course_role? + RoleOverride.enrollment_type_labels.detect { |label| label[:name] == name }[:label].call + elsif name == 'AccountAdmin' RoleOverride::ACCOUNT_ADMIN_LABEL.call else - self.name + name end else - self.name + name end end # Should order course roles so we get "StudentEnrollment", custom student roles, "Teacher Enrollment", custom teacher roles, etc def display_sort_index - if self.course_role? - (ENROLLMENT_TYPES.index(self.base_role_type) * 2) + (self.built_in? ? 0 : 1) + if course_role? + (ENROLLMENT_TYPES.index(base_role_type) * 2) + (built_in? ? 0 : 1) else - self.built_in? ? 0 : 1 + built_in? ? 0 : 1 end end @@ -296,8 +296,8 @@ def self.add_delete_roles_by_user(user, context) def self.compile_manageable_roles(role_data, user, context) # for use with the old sad enrollment dialog granular_admin = context.root_account.feature_enabled?(:granular_permissions_manage_users) - manageable = self.manageable_roles_by_user(user, context) unless granular_admin - addable, deleteable = self.add_delete_roles_by_user(user, context) if granular_admin + manageable = manageable_roles_by_user(user, context) unless granular_admin + addable, deleteable = add_delete_roles_by_user(user, context) if granular_admin role_data.each_with_object([]) { |role, roles| is_manageable = manageable.include?(role[:base_role_name]) unless granular_admin is_addable = addable.include?(role[:base_role_name]) if granular_admin @@ -322,12 +322,12 @@ def self.compile_manageable_roles(role_data, user, context) end def self.role_data(course, user, include_inactive = false) - role_data = self.custom_roles_and_counts_for_course(course, user, include_inactive) - self.compile_manageable_roles(role_data, user, course) + role_data = custom_roles_and_counts_for_course(course, user, include_inactive) + compile_manageable_roles(role_data, user, course) end def self.course_role_data_for_account(account, user) - role_data = self.all_enrollment_roles_for_account(account) - self.compile_manageable_roles(role_data, user, account) + role_data = all_enrollment_roles_for_account(account) + compile_manageable_roles(role_data, user, account) end end diff --git a/app/models/role_override.rb b/app/models/role_override.rb index 5bde40607d3dc..e6224854a7c62 100644 --- a/app/models/role_override.rb +++ b/app/models/role_override.rb @@ -35,7 +35,7 @@ class RoleOverride < ActiveRecord::Base include Role::AssociationHelper def clear_caches - RoleOverride.clear_caches(self.account, self.role) + RoleOverride.clear_caches(account, role) end def self.clear_caches(account, role) @@ -45,7 +45,7 @@ def self.clear_caches(account, role) end def must_apply_to_something - self.errors.add(nil, "Must apply to something") unless applies_to_self? || applies_to_descendants? + errors.add(nil, "Must apply to something") unless applies_to_self? || applies_to_descendants? end def applies_to @@ -1590,7 +1590,7 @@ def self.permissions # permissions that apply to concluded courses/enrollments def self.concluded_permission_types - self.permissions.select { |_k, p| p[:applies_to_concluded] } + permissions.select { |_k, p| p[:applies_to_concluded] } end def self.manageable_permissions(context, base_role_type = nil) @@ -1619,11 +1619,11 @@ def self.manageable_access_token_scopes(context) end def self.readonly_for(context, permission, role, role_context = :role_account) - self.permission_for(context, permission, role, role_context)[:readonly] + permission_for(context, permission, role, role_context)[:readonly] end def self.title_for(context, permission, role, role_context = :role_account) - if self.readonly_for(context, permission, role, role_context) + if readonly_for(context, permission, role, role_context) t 'tooltips.readonly', "you do not have permission to change this." else t 'tooltips.toogle', "Click to toggle this permission ON or OFF" @@ -1631,11 +1631,11 @@ def self.title_for(context, permission, role, role_context = :role_account) end def self.locked_for(context, permission, role, role_context = :role_account) - self.permission_for(context, permission, role, role_context)[:locked] + permission_for(context, permission, role, role_context)[:locked] end def self.hidden_value_for(context, permission, role, role_context = :role_account) - generated_permission = self.permission_for(context, permission, role, role_context) + generated_permission = permission_for(context, permission, role, role_context) if !generated_permission[:readonly] && generated_permission[:explicit] generated_permission[:enabled] ? 'checked' : 'unchecked' else @@ -1656,7 +1656,7 @@ def self.permission_for(context, permission, role_or_role_id, role_context = :ro # we can avoid a query since we're just using it for the batched keys on redis permissionless_base_key = ["role_override_calculation2", Shard.global_id_for(role_or_role_id)].join("/") unless no_caching account = context.is_a?(Account) ? context : Account.new(id: context.account_id) - default_data = self.permissions[permission] + default_data = permissions[permission] if default_data[:account_allows] || no_caching # could depend on anything - can't cache (but that's okay because it's not super common) diff --git a/app/models/rubric.rb b/app/models/rubric.rb index 0c41ef2d24b20..2474af20f62f6 100644 --- a/app/models/rubric.rb +++ b/app/models/rubric.rb @@ -52,32 +52,32 @@ class Rubric < ActiveRecord::Base scope :active, -> { where.not(workflow_state: 'deleted') } set_policy do - given { |user, session| self.context.grants_right?(user, session, :manage_rubrics) } + given { |user, session| context.grants_right?(user, session, :manage_rubrics) } can :read and can :create and can :delete_associations - given { |user, session| self.context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) } + given { |user, session| context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) } can :read and can :create and can :delete_associations - given { |user, session| self.context.grants_right?(user, session, :manage) } + given { |user, session| context.grants_right?(user, session, :manage) } can :read and can :create and can :delete_associations - given { |user, session| self.context.grants_right?(user, session, :read_rubrics) } + given { |user, session| context.grants_right?(user, session, :read_rubrics) } can :read # read_only means "associated with > 1 object for grading purposes" - given { |user, session| !self.read_only && self.rubric_associations.for_grading.length < 2 && self.context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) } + given { |user, session| !read_only && rubric_associations.for_grading.length < 2 && context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) } can :update and can :delete - given { |user, session| !self.read_only && self.rubric_associations.for_grading.length < 2 && self.context.grants_right?(user, session, :manage_rubrics) } + given { |user, session| !read_only && rubric_associations.for_grading.length < 2 && context.grants_right?(user, session, :manage_rubrics) } can :update and can :delete - given { |user, session| self.context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) } + given { |user, session| context.grants_any_right?(user, session, :manage_assignments, :manage_assignments_edit) } can :delete - given { |user, session| self.context.grants_right?(user, session, :manage_rubrics) } + given { |user, session| context.grants_right?(user, session, :manage_rubrics) } can :delete - given { |user, session| self.context.grants_right?(user, session, :read) } + given { |user, session| context.grants_right?(user, session, :read) } can :read end @@ -127,22 +127,22 @@ def default_values end cnt = 0 - siblings = Rubric.where(context_id: self.context_id, context_type: self.context_type).where("workflow_state<>'deleted'") - siblings = siblings.where("id<>?", self.id) unless new_record? - if self.title.present? - original_title = self.title - while siblings.where(title: self.title).exists? + siblings = Rubric.where(context_id: context_id, context_type: context_type).where("workflow_state<>'deleted'") + siblings = siblings.where("id<>?", id) unless new_record? + if title.present? + original_title = title + while siblings.where(title: title).exists? cnt += 1 self.title = "#{original_title} (#{cnt})" end end - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" rescue nil + self.context_code = "#{context_type.underscore}_#{context_id}" rescue nil end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - if self.save + if save rubric_associations.in_batches.destroy_all true end @@ -150,7 +150,7 @@ def destroy def restore self.workflow_state = 'active' - if self.save + if save rubric_associations_with_deleted.where(workflow_state: "deleted").find_each(&:restore) true end @@ -175,7 +175,7 @@ def destroy_for(context, current_user: nil) end if rubric_associations.bookmarked.none? - self.destroy + destroy end end @@ -209,19 +209,19 @@ def data_outcome_ids end def criteria_object - OpenObject.process(self.data) + OpenObject.process(data) end def criteria - self.data + data end def associate_with(association, context, opts = {}) if opts[:purpose] == "grading" - res = self.rubric_associations.where(association_id: association, association_type: association.class.to_s, purpose: 'grading').first + res = rubric_associations.where(association_id: association, association_type: association.class.to_s, purpose: 'grading').first return res if res elsif opts[:update_if_existing] - res = self.rubric_associations.where(association_id: association, association_type: association.class.to_s).first + res = rubric_associations.where(association_id: association, association_type: association.class.to_s).first return res if res end purpose = opts[:purpose] || "unknown" @@ -243,27 +243,27 @@ def update_with_association(current_user, rubric_params, context, association_pa self.user ||= current_user rubric_params[:hide_score_total] ||= association_params[:hide_score_total] @skip_updating_points_possible = association_params[:skip_updating_points_possible] - self.update_criteria(rubric_params) + update_criteria(rubric_params) RubricAssociation.generate(current_user, self, context, association_params) if association_params[:association_object] || association_params[:url] end def unique_item_id(id = nil) @used_ids ||= {} while !id || @used_ids[id] - id = "#{self.rubric_id || self.id}_#{rand(10000)}" + id = "#{rubric_id || self.id}_#{rand(10000)}" end @used_ids[id] = true id end def update_criteria(params) - self.without_versioning(&:save) if self.new_record? + without_versioning(&:save) if new_record? data = generate_criteria(params) - self.hide_score_total = params[:hide_score_total] if self.hide_score_total.nil? || (self.association_count || 0) < 2 + self.hide_score_total = params[:hide_score_total] if hide_score_total.nil? || (association_count || 0) < 2 self.data = data.criteria self.title = data.title self.points_possible = data.points_possible - self.save + save self end @@ -273,12 +273,12 @@ def update_mastery_scales(save = true) mastery_scale = context.resolved_outcome_proficiency return if mastery_scale.nil? - self.data.each do |criterion| + data.each do |criterion| update_criterion_from_mastery_scale(criterion, mastery_scale) end - if self.data_changed? - self.points_possible = total_points_from_criteria(self.data) - self.save! if save + if data_changed? + self.points_possible = total_points_from_criteria(data) + save! if save end end @@ -305,12 +305,12 @@ def update_criterion_from_mastery_scale(criterion, mastery_scale) end def update_learning_outcome_criteria(outcome) - self.data.each do |criterion| + data.each do |criterion| update_learning_outcome_criterion(criterion, outcome) if criterion[:learning_outcome_id] == outcome.id end - if self.data_changed? - self.points_possible = total_points_from_criteria(self.data) - self.save! + if data_changed? + self.points_possible = total_points_from_criteria(data) + save! end end @@ -342,11 +342,11 @@ def criterion_rating(rating_data, criterion_id) def will_change_with_update?(params) params ||= {} - return true if params[:free_form_criterion_comments] && !!self.free_form_criterion_comments != (params[:free_form_criterion_comments] == '1') + return true if params[:free_form_criterion_comments] && !!free_form_criterion_comments != (params[:free_form_criterion_comments] == '1') data = generate_criteria(params) - return true if data.title != self.title || data.points_possible != self.points_possible - return true if Rubric.normalize(data.criteria) != Rubric.normalize(self.criteria) + return true if data.title != title || data.points_possible != points_possible + return true if Rubric.normalize(data.criteria) != Rubric.normalize(criteria) false end @@ -424,9 +424,9 @@ def self.normalize(criteria) def set_root_account_id self.root_account_id ||= if context_type == 'Account' && context.root_account? - self.context.id + context.id else - self.context&.root_account_id + context&.root_account_id end end end diff --git a/app/models/rubric_assessment.rb b/app/models/rubric_assessment.rb index 5ce32fd6a7bd9..112ce5e0a79ad 100644 --- a/app/models/rubric_assessment.rb +++ b/app/models/rubric_assessment.rb @@ -47,9 +47,9 @@ class RubricAssessment < ActiveRecord::Base after_save :track_outcomes def track_outcomes - outcome_ids = (self.data || []).filter_map { |r| r[:learning_outcome_id] }.uniq - peer_review = self.assessment_type == "peer_review" - provisional_grade = self.artifact_type == "ModeratedGrading::ProvisionalGrade" + outcome_ids = (data || []).filter_map { |r| r[:learning_outcome_id] }.uniq + peer_review = assessment_type == "peer_review" + provisional_grade = artifact_type == "ModeratedGrading::ProvisionalGrade" update_outcomes = outcome_ids.present? && !peer_review && !provisional_grade delay_if_production.update_outcomes_for_assessment(outcome_ids) if update_outcomes end @@ -58,14 +58,14 @@ def update_outcomes_for_assessment(outcome_ids = []) return if outcome_ids.empty? alignments = if active_rubric_association? - self.rubric_association.association_object.learning_outcome_alignments.where({ - learning_outcome_id: outcome_ids - }) + rubric_association.association_object.learning_outcome_alignments.where({ + learning_outcome_id: outcome_ids + }) else [] end - (self.data || []).each do |rating| + (data || []).each do |rating| if rating[:learning_outcome_id] alignments.each do |alignment| if alignment.learning_outcome_id == rating[:learning_outcome_id] @@ -93,7 +93,7 @@ def create_outcome_result(alignment) # mastery criterion = rubric_association.rubric.data.find { |c| c[:learning_outcome_id] == alignment.learning_outcome_id } - criterion_result = self.data.find { |c| c[:criterion_id] == criterion[:id] } + criterion_result = data.find { |c| c[:criterion_id] == criterion[:id] } if criterion result.possible = criterion[:points] result.score = criterion_result && criterion_result[:points] @@ -105,11 +105,11 @@ def create_outcome_result(alignment) end # attempt - if self.artifact.is_a?(Submission) - result.attempt = self.artifact.attempt || 1 - result.submitted_at = self.artifact.submitted_at + if artifact.is_a?(Submission) + result.attempt = artifact.attempt || 1 + result.submitted_at = artifact.submitted_at else - result.attempt = self.version_number + result.attempt = version_number end # title @@ -119,8 +119,8 @@ def create_outcome_result(alignment) ) # non-scoring rubrics - result.hide_points = self.hide_points - result.hidden = self.rubric_association.hide_outcome_results + result.hide_points = hide_points + result.hidden = rubric_association.hide_outcome_results result.assessed_at = Time.zone.now result.save_to_version(result.attempt) @@ -128,14 +128,14 @@ def create_outcome_result(alignment) end def update_artifact_parameters - if self.artifact_type == 'Submission' && self.artifact - self.artifact_attempt = self.artifact.attempt + if artifact_type == 'Submission' && artifact + self.artifact_attempt = artifact.attempt end end def htmlify_rating_comments - if self.data_changed? && self.data.present? - self.data.each do |rating| + if data_changed? && data.present? + data.each do |rating| if rating.is_a?(Hash) && rating[:comments].present? rating[:comments_html] = format_message(rating[:comments]).first end @@ -156,23 +156,23 @@ def mark_unread_comments end def update_assessment_requests - requests = self.assessment_requests + requests = assessment_requests if active_rubric_association? - requests += self.rubric_association.assessment_requests.where({ - assessor_id: self.assessor_id, - asset_id: self.artifact_id, - asset_type: self.artifact_type - }) + requests += rubric_association.assessment_requests.where({ + assessor_id: assessor_id, + asset_id: artifact_id, + asset_type: artifact_type + }) end requests.each { |a| - a.attributes = { :rubric_assessment => self, :assessor => self.assessor } + a.attributes = { :rubric_assessment => self, :assessor => assessor } a.complete } end protected :update_assessment_requests def attempt - self.artifact_type == 'Submission' ? self.artifact.attempt : nil + artifact_type == 'Submission' ? artifact.attempt : nil end def set_graded_anonymously @@ -202,35 +202,35 @@ def update_artifact protected :update_artifact set_policy do - given { |user| user && self.assessor_id == user.id } + given { |user| user && assessor_id == user.id } can :create and can :read and can :update - given { |user| user && self.user_id == user.id } + given { |user| user && user_id == user.id } can :read given { |user| user && self.user && - self.rubric_association && - self.rubric_association.context.is_a?(Course) && - self.rubric_association.context.observer_enrollments.where(user_id: user, associated_user: self.user, workflow_state: 'active').exists? + rubric_association && + rubric_association.context.is_a?(Course) && + rubric_association.context.observer_enrollments.where(user_id: user, associated_user: self.user, workflow_state: 'active').exists? } can :read - given { |user, session| self.rubric_association&.grants_right?(user, session, :manage) } + given { |user, session| rubric_association&.grants_right?(user, session, :manage) } can :create and can :read and can :delete - given { |user, session| self.rubric_association&.grants_right?(user, session, :view_rubric_assessments) } + given { |user, session| rubric_association&.grants_right?(user, session, :view_rubric_assessments) } can :read given { |user, session| - self.rubric_association&.grants_right?(user, session, :manage) && - (self.rubric_association.association_object.context.grants_right?(self.assessor, :manage_rubrics) rescue false) + rubric_association&.grants_right?(user, session, :manage) && + (rubric_association.association_object.context.grants_right?(assessor, :manage_rubrics) rescue false) } can :update given { |user, session| - self.can_read_assessor_name?(user, session) + can_read_assessor_name?(user, session) } can :read_assessor end @@ -257,18 +257,18 @@ def score end def assessor_name - self.assessor.short_name rescue t('unknown_user', "Unknown User") + assessor.short_name rescue t('unknown_user', "Unknown User") end def assessment_url - self.artifact.url rescue nil + artifact.url rescue nil end def can_read_assessor_name?(user, session) - self.assessment_type == 'grading' || - !self.considered_anonymous? || - self.assessor_id == user.id || - self.rubric_association.association_object.context.grants_right?( + assessment_type == 'grading' || + !considered_anonymous? || + assessor_id == user.id || + rubric_association.association_object.context.grants_right?( user, session, :view_all_grades ) end @@ -276,19 +276,19 @@ def can_read_assessor_name?(user, session) def considered_anonymous? return false unless active_rubric_association? - self.rubric_association.association_type == 'Assignment' && - self.rubric_association.association_object.anonymous_peer_reviews? + rubric_association.association_type == 'Assignment' && + rubric_association.association_object.anonymous_peer_reviews? end def ratings - self.data + data end def related_group_submissions_and_assessments - if active_rubric_association? && self.rubric_association.association_object.is_a?(Assignment) && !self.artifact.is_a?(ModeratedGrading::ProvisionalGrade) && !self.rubric_association.association_object.grade_group_students_individually - students = self.rubric_association.association_object.group_students(self.user).last + if active_rubric_association? && rubric_association.association_object.is_a?(Assignment) && !artifact.is_a?(ModeratedGrading::ProvisionalGrade) && !rubric_association.association_object.grade_group_students_individually + students = rubric_association.association_object.group_students(user).last students.map do |student| - submission = self.rubric_association.association_object.find_asset_for_assessment(self.rubric_association, student).first + submission = rubric_association.association_object.find_asset_for_assessment(rubric_association, student).first { submission: submission, rubric_assessments: submission.rubric_assessments .where.not(rubric_association: nil) @@ -300,10 +300,10 @@ def related_group_submissions_and_assessments end def set_root_account_id - self.root_account_id ||= self.rubric&.root_account_id + self.root_account_id ||= rubric&.root_account_id end def active_rubric_association? - !!self.rubric_association&.active? + !!rubric_association&.active? end end diff --git a/app/models/rubric_association.rb b/app/models/rubric_association.rb index 4c7497ad98d81..bcd9c5c50686a 100644 --- a/app/models/rubric_association.rb +++ b/app/models/rubric_association.rb @@ -97,7 +97,7 @@ def course_broadcast_data set_broadcast_policy do |p| p.dispatch :rubric_association_created - p.to { self.context.students rescue [] } + p.to { context.students rescue [] } p.whenever { |record| record.just_created && !record.context.is_a?(Course) } @@ -126,8 +126,8 @@ def assert_uniqueness end def assignment - if self.association_object.is_a?(Assignment) - self.association_object + if association_object.is_a?(Assignment) + association_object else nil end @@ -136,38 +136,38 @@ def assignment def update_alignments return unless assignment - outcome_ids = self.deleted? ? [] : rubric.learning_outcome_alignments.map(&:learning_outcome_id) + outcome_ids = deleted? ? [] : rubric.learning_outcome_alignments.map(&:learning_outcome_id) LearningOutcome.update_alignments(assignment, context, outcome_ids) true end def touch_association - if self.association_type == "Assignment" + if association_type == "Assignment" self.class.connection.after_transaction_commit do - self.association_object.touch + association_object.touch end end end def update_old_rubric - if self.rubric_id_changed? && self.rubric_id_was && self.rubric_id_was != self.rubric_id - rubric = Rubric.find(self.rubric_id_was) + if rubric_id_changed? && rubric_id_was && rubric_id_was != rubric_id + rubric = Rubric.find(rubric_id_was) rubric.destroy if rubric.rubric_associations.count == 0 && rubric.rubric_assessments.count == 0 end end def context_name - @cached_context_name ||= self.shard.activate do - Rails.cache.fetch(['short_name_lookup', self.context_code].cache_key) do - self.context.short_name rescue "" + @cached_context_name ||= shard.activate do + Rails.cache.fetch(['short_name_lookup', context_code].cache_key) do + context.short_name rescue "" end end end def update_values - self.bookmarked = true if self.purpose == 'bookmark' || self.bookmarked.nil? - self.context_code ||= "#{self.context_type.underscore}_#{self.context_id}" rescue nil - self.title ||= (self.association_object.title rescue self.association_object.name) rescue nil + self.bookmarked = true if purpose == 'bookmark' || bookmarked.nil? + self.context_code ||= "#{context_type.underscore}_#{context_id}" rescue nil + self.title ||= (association_object.title rescue association_object.name) rescue nil self.workflow_state ||= "active" end protected :update_values @@ -175,49 +175,49 @@ def update_values def user_can_assess_for?(assessor: nil, assessee: nil) raise "assessor and assessee required" unless assessor && assessee - self.context.grants_right?(assessor, :manage_grades) || self.assessment_requests.incomplete.for_assessee(assessee).pluck(:assessor_id).include?(assessor.id) + context.grants_right?(assessor, :manage_grades) || assessment_requests.incomplete.for_assessee(assessee).pluck(:assessor_id).include?(assessor.id) end def user_did_assess_for?(assessor: nil, assessee: nil) raise "assessor and assessee required" unless assessor && assessee - self.assessment_requests.complete.for_assessee(assessee).for_assessor(assessor).any? + assessment_requests.complete.for_assessee(assessee).for_assessor(assessor).any? end set_policy do - given { |user, session| self.context.grants_right?(user, session, :manage_rubrics) } + given { |user, session| context.grants_right?(user, session, :manage_rubrics) } can :update and can :delete and can :manage - given { |user, session| self.context.grants_right?(user, session, :participate_as_student) } + given { |user, session| context.grants_right?(user, session, :participate_as_student) } can :submit - given { |user, session| self.context.grants_right?(user, session, :view_all_grades) } + given { |user, session| context.grants_right?(user, session, :view_all_grades) } can :view_rubric_assessments end def update_assignment_points - if self.use_for_grading && !self.skip_updating_points_possible && self.association_object && self.association_object.respond_to?(:points_possible=) && self.rubric && self.rubric.points_possible && self.association_object.points_possible != self.rubric.points_possible - self.association_object.points_possible = self.rubric.points_possible - self.association_object.save + if use_for_grading && !skip_updating_points_possible && association_object && association_object.respond_to?(:points_possible=) && rubric && rubric.points_possible && association_object.points_possible != rubric.points_possible + association_object.points_possible = rubric.points_possible + association_object.save end end protected :update_assignment_points def remind_user(assessee) - assessment_request = self.assessment_requests.where(user_id: assessee).first - assessment_request ||= self.assessment_requests.build(:user => assessee) + assessment_request = assessment_requests.where(user_id: assessee).first + assessment_request ||= assessment_requests.build(:user => assessee) assessment_request.send_reminder! if assessment_request.assigned? assessment_request end def update_rubric - cnt = self.rubric.rubric_associations.for_grading.length rescue 0 - self.rubric&.with_versioning(false) do - self.rubric.read_only = cnt > 1 - self.rubric.association_count = cnt - self.rubric.save + cnt = rubric.rubric_associations.for_grading.length rescue 0 + rubric&.with_versioning(false) do + rubric.read_only = cnt > 1 + rubric.association_count = cnt + rubric.save - self.rubric.destroy if cnt == 0 && self.rubric.rubric_associations.count == 0 && !self.rubric.public + rubric.destroy if cnt == 0 && rubric.rubric_associations.count == 0 && !rubric.public end end protected :update_rubric @@ -229,8 +229,8 @@ def link_to_assessments # Go up to the assignment and loop through all submissions. # Update each submission's assessment_requests with a link to this rubric association # but only if not already associated - if self.association_id && self.association_type == 'Assignment' - self.association_object.submissions.each do |sub| + if association_id && association_type == 'Assignment' + association_object.submissions.each do |sub| sub.assessment_requests.where(:rubric_association_id => nil).update_all(:rubric_association_id => id, :workflow_state => 'assigned') end end @@ -238,7 +238,7 @@ def link_to_assessments protected :link_to_assessments def unsubmitted_users - self.context.students - self.rubric_assessments.map(&:user) - self.assessment_requests.map(&:user) + context.students - rubric_assessments.map(&:user) - assessment_requests.map(&:user) end def self.generate(current_user, rubric, context, params) @@ -277,11 +277,11 @@ def self.generate(current_user, rubric, context, params) end def assessments_unique_per_asset?(assessment_type) - self.association_object.is_a?(Assignment) && self.purpose == "grading" && assessment_type == "grading" + association_object.is_a?(Assignment) && purpose == "grading" && assessment_type == "grading" end def assessment_points(criterion, data) - if criterion.learning_outcome_id && !self.context.feature_enabled?(:outcome_extra_credit) + if criterion.learning_outcome_id && !context.feature_enabled?(:outcome_extra_credit) [criterion.points, data[:points].to_f].min else data[:points].to_f @@ -301,15 +301,15 @@ def assess(opts = {}) raise "Assessment type required for assessing" unless params[:assessment_type] if opts[:artifact].is_a?(Quizzes::QuizSubmission) - opts[:artifact] = self.association_object.find_or_create_submission(opts[:artifact].user) + opts[:artifact] = association_object.find_or_create_submission(opts[:artifact].user) end - if self.association_object.is_a?(Assignment) && !self.association_object.grade_group_students_individually - group, students_to_assess = self.association_object.group_students(opts[:artifact].student) + if association_object.is_a?(Assignment) && !association_object.grade_group_students_individually + group, students_to_assess = association_object.group_students(opts[:artifact].student) if group provisional_grader = opts[:artifact].is_a?(ModeratedGrading::ProvisionalGrade) && opts[:assessor] artifacts_to_assess = students_to_assess.map do |student| - self.association_object.find_asset_for_assessment(self, student, :provisional_grader => provisional_grader).first + association_object.find_asset_for_assessment(self, student, :provisional_grader => provisional_grader).first end else artifacts_to_assess = [opts[:artifact]] @@ -322,7 +322,7 @@ def assess(opts = {}) score = nil replace_ratings = false has_score = false - self.rubric.criteria_object.each do |criterion| + rubric.criteria_object.each do |criterion| data = params["criterion_#{criterion.id}".to_sym] rating = {} if data @@ -357,7 +357,7 @@ def assess(opts = {}) self.summary_data[:saved_comments][criterion.id.to_s] << rating[:comments] # TODO i18n self.summary_data[:saved_comments][criterion.id.to_s] = self.summary_data[:saved_comments][criterion.id.to_s].select { |desc| desc && !desc.empty? && desc != "No Details" }.uniq.sort - self.save + save end rating[:description] = t('no_details', "No details") if !rating[:description] || rating[:description].empty? ratings << rating @@ -375,7 +375,7 @@ def assess(opts = {}) # Assessments are unique per artifact/assessor/assessment_type. assessment = association.rubric_assessments.where(artifact_id: artifact, artifact_type: artifact.class.to_s, assessor_id: opts[:assessor], assessment_type: params[:assessment_type]).first end - assessment ||= association.rubric_assessments.build(:assessor => opts[:assessor], :artifact => artifact, :user => artifact.student, :rubric => self.rubric, :assessment_type => params[:assessment_type]) + assessment ||= association.rubric_assessments.build(:assessor => opts[:assessor], :artifact => artifact, :user => artifact.student, :rubric => rubric, :assessment_type => params[:assessment_type]) assessment.score = score if replace_ratings assessment.data = ratings if replace_ratings @@ -425,9 +425,9 @@ def record_deletion_audit_event def set_root_account_id self.root_account_id ||= if context_type == 'Account' && context.root_account? - self.context.id + context.id else - self.context&.root_account_id + context&.root_account_id end end end diff --git a/app/models/session_persistence_token.rb b/app/models/session_persistence_token.rb index 54f072c11451b..1b60f6f0d770a 100644 --- a/app/models/session_persistence_token.rb +++ b/app/models/session_persistence_token.rb @@ -51,12 +51,12 @@ def self.generate(pseudonym) pseudonym.session_persistence_tokens.create!( :token_salt => salt, :uncrypted_token => token, - :crypted_token => self.hashed_token(salt, token) + :crypted_token => hashed_token(salt, token) ) end def self.hashed_token(salt, token) - self.crypto.encrypt(salt, token) + crypto.encrypt(salt, token) end def self.crypto @@ -67,7 +67,7 @@ def self.find_by_pseudonym_credentials(creds) token_id, persistence_token, uuid = creds.split("::") return unless token_id.present? && persistence_token.present? && uuid.present? - token = self.where(id: token_id).first + token = where(id: token_id).first return unless token return unless token.valid_token?(persistence_token, uuid) @@ -81,9 +81,9 @@ def self.delete_expired(since) def valid_token?(persistence_token, uncrypted_token) # if the pseudonym is marked deleted, the token can still be marked as # valid, but the actual login step will fail as expected. - self.pseudonym && - self.pseudonym.persistence_token == persistence_token && - self.class.crypto.matches?(self.crypted_token, self.token_salt, uncrypted_token) + pseudonym && + pseudonym.persistence_token == persistence_token && + self.class.crypto.matches?(crypted_token, token_salt, uncrypted_token) end def pseudonym_credentials diff --git a/app/models/shared_brand_config.rb b/app/models/shared_brand_config.rb index 2be318c2c9b9f..f13d42904acc6 100644 --- a/app/models/shared_brand_config.rb +++ b/app/models/shared_brand_config.rb @@ -24,7 +24,7 @@ class SharedBrandConfig < ActiveRecord::Base validates :brand_config, presence: true set_policy do - given { |user, session| self.account.grants_right?(user, session, :manage_account_settings) } + given { |user, session| account.grants_right?(user, session, :manage_account_settings) } can :create and can :update and can :delete end end diff --git a/app/models/sis_batch.rb b/app/models/sis_batch.rb index 34f4eb58cf28a..e957f6806646d 100644 --- a/app/models/sis_batch.rb +++ b/app/models/sis_batch.rb @@ -59,7 +59,7 @@ def self.valid_import_types end set_policy do - given { |user| self.account.grants_any_right?(user, :manage_sis, :import_sis) } + given { |user| account.grants_any_right?(user, :manage_sis, :import_sis) } can :read end @@ -133,7 +133,7 @@ def self.rows_for_parallel(rows) end def process - self.class.queue_job_for_account(self.account) + self.class.queue_job_for_account(account) end def enable_diffing(data_set_id, opts = {}) @@ -184,42 +184,42 @@ def on_permanent_failure(_error) # can rename this to something more sensible. def process_without_send_later self.class.transaction do - if self.workflow_state == 'aborted' + if workflow_state == 'aborted' self.progress = 100 - self.save + save return end - if self.workflow_state == 'created' + if workflow_state == 'created' self.workflow_state = :importing self.progress = 0 self.started_at = Time.now.utc - self.save + save else return end end - import_scheme = SisBatch.valid_import_types[self.data[:import_type]] + import_scheme = SisBatch.valid_import_types[data[:import_type]] if import_scheme.nil? - self.data[:error_message] = t 'errors.unrecorgnized_type', "Unrecognized import type" + data[:error_message] = t 'errors.unrecorgnized_type', "Unrecognized import type" self.workflow_state = :failed - self.save + save return end import_scheme[:callback].call(self) rescue => e - self.reload # might have failed trying to save + reload # might have failed trying to save self.data ||= {} self.data[:error_message] = e.to_s self.data[:stack_trace] = "#{e}\n#{e.backtrace.join("\n")}" self.workflow_state = "failed" - self.save + save end def abort_batch SisBatch.not_completed.where(id: self).update_all(workflow_state: 'aborted', updated_at: Time.zone.now) - self.class.queue_job_for_account(account, 10.minutes.from_now) if self.account.sis_batches.needs_processing.exists? + self.class.queue_job_for_account(account, 10.minutes.from_now) if account.sis_batches.needs_processing.exists? end def batch_aborted(message) @@ -228,7 +228,7 @@ def batch_aborted(message) end def self.abort_all_pending_for_account(account) - self.transaction do + transaction do account.sis_batches.not_started.lock(:no_key_update).order(:id).find_in_batches do |batch| SisBatch.where(id: batch).update_all(workflow_state: 'aborted', progress: 100) end @@ -246,7 +246,7 @@ def self.strand_for_account(account) end def skip_deletes? - !!self.options[:skip_deletes] + !!options[:skip_deletes] end def self.process_all_for_account(account) @@ -273,19 +273,19 @@ def self.process_all_for_account(account) end def fast_update_progress(val) - return true if val == self.progress + return true if val == progress self.progress = val state = SisBatch.connection.select_value(<<~SQL.squish) - UPDATE #{SisBatch.quoted_table_name} SET progress=#{val} WHERE id=#{self.id} RETURNING workflow_state + UPDATE #{SisBatch.quoted_table_name} SET progress=#{val} WHERE id=#{id} RETURNING workflow_state SQL raise SisBatch::Aborted if state == 'aborted' end def importing? - self.workflow_state == 'importing' || - self.workflow_state == 'created' || - self.workflow_state == 'cleanup_batch' + workflow_state == 'importing' || + workflow_state == 'created' || + workflow_state == 'cleanup_batch' end def process_instructure_csv_zip @@ -293,11 +293,11 @@ def process_instructure_csv_zip download_zip diff_result = generate_diff if diff_result == :empty_diff_file - self.finish(true) + finish(true) return end - SIS::CSV::ImportRefactored.process(self.account, + SIS::CSV::ImportRefactored.process(account, files: [@data_file.path], batch: self, override_sis_stickiness: options[:override_sis_stickiness], @@ -313,17 +313,17 @@ def compute_file_size(file) end def generate_diff - return if self.diffing_remaster # joined the chain, but don't actually want to diff this one - return unless self.diffing_data_set_identifier + return if diffing_remaster # joined the chain, but don't actually want to diff this one + return unless diffing_data_set_identifier # the previous batch may not have had diffing applied because of the change_threshold, # so look for the latest one with a generated_diff_id (or a remaster) - previous_batch = self.account.sis_batches - .succeeded.where(diffing_data_set_identifier: self.diffing_data_set_identifier) - .where("diffing_remaster = 't' OR generated_diff_id IS NOT NULL").order(:created_at).last + previous_batch = account.sis_batches + .succeeded.where(diffing_data_set_identifier: diffing_data_set_identifier) + .where("diffing_remaster = 't' OR generated_diff_id IS NOT NULL").order(:created_at).last # otherwise, the previous one may have been the first batch so fallback to the original query - previous_batch ||= self.account.sis_batches - .succeeded.where(diffing_data_set_identifier: self.diffing_data_set_identifier).order(:created_at).first + previous_batch ||= account.sis_batches + .succeeded.where(diffing_data_set_identifier: diffing_data_set_identifier).order(:created_at).first previous_zip = previous_batch.try(:download_zip) return unless previous_zip @@ -335,12 +335,12 @@ def generate_diff return end - diff = SIS::CSV::DiffGenerator.new(self.account, self).generate(previous_zip.path, @data_file.path) + diff = SIS::CSV::DiffGenerator.new(account, self).generate(previous_zip.path, @data_file.path) return :empty_diff_file unless diff # just end if there's nothing to import diffed_data_file = diff[:file_io] - if self.diff_row_count_threshold && diff[:row_count] > self.diff_row_count_threshold + if diff_row_count_threshold && diff[:row_count] > diff_row_count_threshold diffed_data_file.close SisBatch.add_error(nil, "Diffing not performed because difference row count exceeded threshold", sis_batch: self) return @@ -351,20 +351,20 @@ def generate_diff self.generated_diff = Attachment.create_data_attachment( self, Rack::Test::UploadedFile.new(diffed_data_file.path, 'application/zip'), - t(:diff_filename, "sis_upload_diffed_%{id}.zip", :id => self.id) + t(:diff_filename, "sis_upload_diffed_%{id}.zip", :id => id) ) - self.save! + save! # Success, swap out the original update for this new diff and continue. @data_file.try(:close) @data_file = diffed_data_file end def diff_row_count_threshold=(val) - self.options[:diff_row_count_threshold] = val + options[:diff_row_count_threshold] = val end def diff_row_count_threshold - self.options[:diff_row_count_threshold] + options[:diff_row_count_threshold] end def file_diff_percent(current_file_size, previous_zip_size) @@ -375,7 +375,7 @@ def download_zip @data_file = if self.data[:file_path] File.open(self.data[:file_path], 'rb') else - self.attachment.open(:need_local_file => true) + attachment.open(:need_local_file => true) end @data_file end @@ -385,19 +385,19 @@ def finish(import_finished) @data_file = nil return self if workflow_state == 'aborted' - remove_previous_imports if self.batch_mode? && import_finished - @has_errors = self.sis_batch_errors.exists? - import_finished = !(@has_errors && self.sis_batch_errors.failed.exists?) if import_finished + remove_previous_imports if batch_mode? && import_finished + @has_errors = sis_batch_errors.exists? + import_finished = !(@has_errors && sis_batch_errors.failed.exists?) if import_finished finalize_workflow_state(import_finished) delay_if_production(max_attempts: 5).write_errors_to_file if @has_errors populate_old_warnings_and_errors statistics self.progress = 100 if import_finished self.ended_at = Time.now.utc - self.save! + save! InstStatsd::Statsd.increment("sis_batch_completed", tags: { failed: @has_errors }) - if !self.data[:running_immediately] && self.account.sis_batches.needs_processing.exists? + if !self.data[:running_immediately] && account.sis_batches.needs_processing.exists? self.class.queue_job_for_account(account) # check if there's anything that needs to be run end end @@ -494,7 +494,7 @@ def stat_restored_from(type) end def batch_mode_terms - if self.options[:multi_term_batch_mode] + if options[:multi_term_batch_mode] @terms ||= EnrollmentTerm.where(sis_batch_id: self) unless @terms.exists? abort_batch @@ -502,7 +502,7 @@ def batch_mode_terms end @terms else - self.batch_mode_term + batch_mode_term end end @@ -528,7 +528,7 @@ def remove_non_batch_courses(courses, total_rows, current_row) finish_course_destroy(batch) current_row += count course_count += count - self.fast_update_progress(current_row.to_f / total_rows * 100) + fast_update_progress(current_row.to_f / total_rows * 100) end self.data[:counts][:batch_courses_deleted] = course_count @@ -537,7 +537,7 @@ def remove_non_batch_courses(courses, total_rows, current_row) def finish_course_destroy(courses) courses.each do |course| - Auditors::Course.record_deleted(course, self.user, source: :sis, sis_batch: self) + Auditors::Course.record_deleted(course, user, source: :sis, sis_batch: self) og_sticky = course.stuck_sis_fields course.clear_sis_stickiness(:workflow_state) course.skip_broadcasts = true @@ -547,7 +547,7 @@ def finish_course_destroy(courses) def term_sections_scope if data[:supplied_batches].include?(:section) - scope = self.account.course_sections.active.where(courses: { enrollment_term_id: batch_mode_terms }) + scope = account.course_sections.active.where(courses: { enrollment_term_id: batch_mode_terms }) scope = scope.where.not(sis_batch_id: nil).where.not(sis_source_id: nil) scope.joins("INNER JOIN #{Course.quoted_table_name} ON courses.id=COALESCE(nonxlist_course_id, course_id)").readonly(false) end @@ -574,7 +574,7 @@ def remove_non_batch_sections(sections, _total_rows, current_row) def term_enrollments_scope if data[:supplied_batches].include?(:enrollment) - scope = self.account.enrollments.active.joins(:course).readonly(false).where.not(sis_batch_id: nil) + scope = account.enrollments.active.joins(:course).readonly(false).where.not(sis_batch_id: nil) scope.where(courses: { enrollment_term_id: batch_mode_terms }) end end @@ -607,7 +607,7 @@ def remove_non_batch_enrollments(enrollments, total_rows, current_row) batch_count = data.count { |d| d.context_type == "Enrollment" } # data can include group membership deletions enrollment_count += batch_count current_row += batch_count - self.fast_update_progress(current_row.to_f / total_rows * 100) + fast_update_progress(current_row.to_f / total_rows * 100) end self.data[:counts][:batch_enrollments_deleted] = enrollment_count current_row @@ -620,11 +620,11 @@ def remove_previous_imports # ^reloading the whole batch can be a problem because we might be tracking data # we haven't persisted yet on model attributes... if ['failed', 'failed_with_messages', 'aborted'].include?(current_workflow_state) - Rails.logger.info("[SIS_BATCH] Refusing to cleanup after batch #{self.id} because workflow state is #{current_workflow_state}") + Rails.logger.info("[SIS_BATCH] Refusing to cleanup after batch #{id} because workflow state is #{current_workflow_state}") return false end # we shouldn't be able to get here without a term, but if we do, skip - return unless self.batch_mode_term || options[:multi_term_batch_mode] + return unless batch_mode_term || options[:multi_term_batch_mode] supplied_batches = data[:supplied_batches].dup.keep_if { |i| [:course, :section, :enrollment].include? i } return unless supplied_batches.present? @@ -643,7 +643,7 @@ def remove_previous_imports row = remove_non_batch_sections(sections, count, row) if sections remove_non_batch_courses(courses, count, row) if courses rescue SisBatch::Aborted - self.reload + reload end end @@ -688,30 +688,30 @@ def change_detected_message(count, type) def as_json(**) data = { - "id" => self.id, - "created_at" => self.created_at, - "started_at" => self.started_at, - "ended_at" => self.ended_at, - "updated_at" => self.updated_at, - "progress" => self.progress, - "workflow_state" => self.workflow_state, + "id" => id, + "created_at" => created_at, + "started_at" => started_at, + "ended_at" => ended_at, + "updated_at" => updated_at, + "progress" => progress, + "workflow_state" => workflow_state, "data" => self.data, - "batch_mode" => self.batch_mode, - "batch_mode_term_id" => self.batch_mode_term ? self.batch_mode_term.id : nil, - "multi_term_batch_mode" => self.options[:multi_term_batch_mode], - "override_sis_stickiness" => self.options[:override_sis_stickiness], - "add_sis_stickiness" => self.options[:add_sis_stickiness], - "update_sis_id_if_login_claimed" => self.options[:update_sis_id_if_login_claimed], - "clear_sis_stickiness" => self.options[:clear_sis_stickiness], - "diffing_data_set_identifier" => self.diffing_data_set_identifier, - "diffed_against_import_id" => self.options[:diffed_against_sis_batch_id], - "diffing_drop_status" => self.options[:diffing_drop_status], - "skip_deletes" => self.options[:skip_deletes], - "change_threshold" => self.change_threshold, - "diff_row_count_threshold" => self.options[:diff_row_count_threshold] + "batch_mode" => batch_mode, + "batch_mode_term_id" => batch_mode_term ? batch_mode_term.id : nil, + "multi_term_batch_mode" => options[:multi_term_batch_mode], + "override_sis_stickiness" => options[:override_sis_stickiness], + "add_sis_stickiness" => options[:add_sis_stickiness], + "update_sis_id_if_login_claimed" => options[:update_sis_id_if_login_claimed], + "clear_sis_stickiness" => options[:clear_sis_stickiness], + "diffing_data_set_identifier" => diffing_data_set_identifier, + "diffed_against_import_id" => options[:diffed_against_sis_batch_id], + "diffing_drop_status" => options[:diffing_drop_status], + "skip_deletes" => options[:skip_deletes], + "change_threshold" => change_threshold, + "diff_row_count_threshold" => options[:diff_row_count_threshold] } - data["processing_errors"] = self.processing_errors if self.processing_errors.present? - data["processing_warnings"] = self.processing_warnings if self.processing_warnings.present? + data["processing_errors"] = processing_errors if processing_errors.present? + data["processing_warnings"] = processing_warnings if processing_warnings.present? data end @@ -723,17 +723,17 @@ def populate_old_warnings_and_errors self.data[:counts][:warning_count] = 0 return end - fail_count = self.sis_batch_errors.failed.count - warning_count = self.sis_batch_errors.warnings.count - self.processing_errors = self.sis_batch_errors.failed.limit(24).pluck(:file, :message) - self.processing_warnings = self.sis_batch_errors.warnings.limit(24).pluck(:file, :message) + fail_count = sis_batch_errors.failed.count + warning_count = sis_batch_errors.warnings.count + self.processing_errors = sis_batch_errors.failed.limit(24).pluck(:file, :message) + self.processing_warnings = sis_batch_errors.warnings.limit(24).pluck(:file, :message) if fail_count > 24 - self.processing_errors << ["and #{fail_count - 24} more errors that were not included", - "Download the error file to see all errors."] + processing_errors << ["and #{fail_count - 24} more errors that were not included", + "Download the error file to see all errors."] end if warning_count > 24 - self.processing_warnings << ["and #{warning_count - 24} more warnings that were not included", - "Download the error file to see all warnings."] + processing_warnings << ["and #{warning_count - 24} more warnings that were not included", + "Download the error file to see all warnings."] end self.data[:counts][:error_count] = fail_count self.data[:counts][:warning_count] = warning_count @@ -743,7 +743,7 @@ def write_errors_to_file file = temp_error_file_path CSV.open(file, "w") do |csv| csv << %w[sis_import_id file message row] - self.sis_batch_errors.find_each do |error| + sis_batch_errors.find_each do |error| row = [] row << error.sis_batch_id row << error.file @@ -757,11 +757,11 @@ def write_errors_to_file Rack::Test::UploadedFile.new(file, 'csv', true), "sis_errors_attachment_#{id}.csv" ) - self.save! if Rails.env.production? + save! if Rails.env.production? end def temp_error_file_path - temp = Tempfile.open([self.global_id.to_s + '_processing_warnings_and_errors' + Time.zone.now.to_s, '.csv']) + temp = Tempfile.open([global_id.to_s + '_processing_warnings_and_errors' + Time.zone.now.to_s, '.csv']) file = temp.path temp.close! file @@ -866,7 +866,7 @@ def finalize_enrollments(ids) end def restore_states_later(batch_mode: nil, undelete_only: false, unconclude_only: false) - self.shard.activate do + shard.activate do restore_progress = Progress.create! context: self, tag: "sis_batch_state_restore", completion: 0.0 restore_progress.process_job(self, :restore_states_for_batch, { n_strand: ["restore_states_for_batch", account.global_id] }, @@ -877,8 +877,8 @@ def restore_states_later(batch_mode: nil, undelete_only: false, unconclude_only: def restore_states_for_batch(restore_progress = nil, batch_mode: false, undelete_only: false, unconclude_only: false) restore_progress&.start - self.update_attribute(:workflow_state, 'restoring') - roll_back = self.roll_back_data + update_attribute(:workflow_state, 'restoring') + roll_back = roll_back_data roll_back = roll_back.where(updated_workflow_state: %w[retired deleted]) if undelete_only roll_back = roll_back.where(updated_workflow_state: %w[completed]) if unconclude_only roll_back = roll_back.where(batch_mode_delete: batch_mode) if batch_mode @@ -896,7 +896,7 @@ def restore_states_for_batch(restore_progress = nil, batch_mode: false, undelete self.workflow_state = (undelete_only || unconclude_only || batch_mode) ? 'partially_restored' : 'restored' tags = { undelete_only: undelete_only, unconclude_only: unconclude_only, batch_mode: batch_mode } InstStatsd::Statsd.increment("sis_batch_restored", tags: tags) - self.save! + save! end def add_restore_statistics @@ -931,7 +931,7 @@ def restore_sql(type, data) def self.load_downloadable_attachments(batches) batches = Array(batches) all_ids = batches.map { |sb| sb.data&.dig(:downloadable_attachment_ids) || [] }.flatten - all_attachments = all_ids.any? ? Attachment.where(:context_type => self.name, :context_id => batches, :id => all_ids).to_a.group_by(&:context_id) : {} + all_attachments = all_ids.any? ? Attachment.where(:context_type => name, :context_id => batches, :id => all_ids).to_a.group_by(&:context_id) : {} batches.each do |b| b.downloadable_attachments = all_attachments[b.id] || [] end @@ -940,7 +940,7 @@ def self.load_downloadable_attachments(batches) def downloadable_attachments(type = :all) return [] unless data - self.shard.activate do + shard.activate do @downloadable_attachments ||= begin ids = data[:downloadable_attachment_ids] diff --git a/app/models/sis_batch_error.rb b/app/models/sis_batch_error.rb index c2f5a1655f9df..2169a26e8a802 100644 --- a/app/models/sis_batch_error.rb +++ b/app/models/sis_batch_error.rb @@ -31,6 +31,6 @@ def self.cleanup_old_errors end def description - (self.file || "") + " - " + (self.message || "") + (file || "") + " - " + (message || "") end end diff --git a/app/models/sis_pseudonym.rb b/app/models/sis_pseudonym.rb index db12af347bca2..8d4113ed8acd1 100644 --- a/app/models/sis_pseudonym.rb +++ b/app/models/sis_pseudonym.rb @@ -25,7 +25,7 @@ def self.for(user, context, type: :exact, require_sis: true, include_deleted: fa raise ArgumentError("context must respond to .root_account") unless root_account&.root_account? || context.respond_to?(:root_account) sis_pseudonym = - self.new(user, context, type, require_sis, include_deleted, root_account, in_region: in_region, include_all_pseudonyms: include_all_pseudonyms) + new(user, context, type, require_sis, include_deleted, root_account, in_region: in_region, include_all_pseudonyms: include_all_pseudonyms) include_all_pseudonyms ? sis_pseudonym.all_pseudonyms : sis_pseudonym.pseudonym end diff --git a/app/models/stream_item.rb b/app/models/stream_item.rb index e56c8d9977682..6c9b368e92211 100644 --- a/app/models/stream_item.rb +++ b/app/models/stream_item.rb @@ -39,13 +39,13 @@ class StreamItem < ActiveRecord::Base before_save :ensure_notification_category def ensure_notification_category - if self.asset_type == 'Message' + if asset_type == 'Message' self.notification_category ||= get_notification_category end end def get_notification_category - self.read_attribute(:data)['notification_category'] || self.data.notification_category + read_attribute(:data)['notification_category'] || data.notification_category end def self.reconstitute_ar_object(type, data) @@ -100,7 +100,7 @@ def self.reconstitute_ar_object(type, data) def data(viewing_user_id = nil) # reconstitute AR objects - @ar_data ||= self.shard.activate do + @ar_data ||= shard.activate do self.class.reconstitute_ar_object(asset_type, read_attribute(:data)) end res = @ar_data @@ -148,14 +148,14 @@ def prepare_conversation(conversation) def regenerate!(obj = nil) obj ||= asset - return nil if self.asset_type == 'Message' && self.asset_id.nil? + return nil if asset_type == 'Message' && asset_id.nil? if !obj || (obj.respond_to?(:workflow_state) && obj.workflow_state == 'deleted') - self.destroy + destroy return nil end res = generate_data(obj) - self.save + save res end @@ -216,8 +216,8 @@ def generate_data(object) else raise "Unexpected stream item type: #{object.class}" end - if self.context_type - res['context_short_name'] = Rails.cache.fetch(['short_name_lookup', "#{self.context_type.underscore}_#{self.context_id}"].cache_key) do + if context_type + res['context_short_name'] = Rails.cache.fetch(['short_name_lookup', "#{context_type.underscore}_#{context_id}"].cache_key) do self.context.short_name rescue '' end end @@ -243,7 +243,7 @@ def self.generate_or_update(object) return item if item end - item = self.new + item = new item.generate_data(object) StreamItem.unique_constraint_retry do |retry_count| retry_count == 0 ? item.save! : item = nil # if it fails just carry on - it got created somewhere else so grab it later @@ -414,10 +414,10 @@ def self.destroy_stream_items(before_date, touch_users = true) def associated_shards if self.context.try(:respond_to?, :associated_shards) self.context.associated_shards - elsif self.data.respond_to?(:associated_shards) - self.data.associated_shards + elsif data.respond_to?(:associated_shards) + data.associated_shards else - [self.shard] + [shard] end end @@ -469,13 +469,13 @@ def post_process(res, viewing_user_id) public def destroy_stream_item_instances - self.stream_item_instances.shard(self).activate do |scope| + stream_item_instances.shard(self).activate do |scope| user_ids = scope.pluck(:user_id) - if !self.invalidate_immediately && user_ids.count > 100 + if !invalidate_immediately && user_ids.count > 100 StreamItemCache.delay_if_production(priority: Delayed::LOW_PRIORITY) - .invalidate_all_recent_stream_items(user_ids, self.context_type, self.context_id) + .invalidate_all_recent_stream_items(user_ids, context_type, context_id) else - StreamItemCache.invalidate_all_recent_stream_items(user_ids, self.context_type, self.context_id) + StreamItemCache.invalidate_all_recent_stream_items(user_ids, context_type, context_id) end scope.delete_all nil diff --git a/app/models/stream_item_instance.rb b/app/models/stream_item_instance.rb index 42bed19f59705..98487301957be 100644 --- a/app/models/stream_item_instance.rb +++ b/app/models/stream_item_instance.rb @@ -46,7 +46,7 @@ def update_all(*) # is an array of [context_type, context_id]) def update_all_with_invalidation(contexts, updates) contexts.each { |context| StreamItemCache.invalidate_context_stream_item_key(context.first, context.last) } - self.original_update_all(updates) + original_update_all(updates) end end diff --git a/app/models/student_enrollment.rb b/app/models/student_enrollment.rb index ef9e411011359..438a9754657f7 100644 --- a/app/models/student_enrollment.rb +++ b/app/models/student_enrollment.rb @@ -35,10 +35,10 @@ def student? end def evaluate_modules - ContextModuleProgression.for_user(self.user_id) + ContextModuleProgression.for_user(user_id) .joins(:context_module) .readonly(false) - .where(:context_modules => { :context_type => 'Course', :context_id => self.course_id }) + .where(:context_modules => { :context_type => 'Course', :context_id => course_id }) .each(&:mark_as_outdated!) end diff --git a/app/models/submission.rb b/app/models/submission.rb index b1f003ec0631c..78371fe10cd31 100644 --- a/app/models/submission.rb +++ b/app/models/submission.rb @@ -365,7 +365,7 @@ def reset_regraded def autograded? # AutoGrader == (quiz_id * -1) - !!(self.grader_id && self.grader_id < 0) + !!(grader_id && grader_id < 0) end after_create :needs_grading_count_updated, if: :needs_grading? @@ -373,7 +373,7 @@ def autograded? after_update :update_planner_override def needs_grading_count_updated self.class.connection.after_transaction_commit do - self.assignment.clear_cache_key(:needs_grading) + assignment.clear_cache_key(:needs_grading) end end @@ -381,7 +381,7 @@ def needs_grading_count_updated after_update :assignment_submission_count_updated, if: :submitted_changed? def assignment_submission_count_updated self.class.connection.after_transaction_commit do - Rails.cache.delete(['submitted_count', self.assignment].cache_key) + Rails.cache.delete(['submitted_count', assignment].cache_key) end end @@ -389,18 +389,18 @@ def assignment_submission_count_updated after_update :assignment_graded_count_updated, if: :graded_changed? def assignment_graded_count_updated self.class.connection.after_transaction_commit do - Rails.cache.delete(['graded_count', self.assignment].cache_key) + Rails.cache.delete(['graded_count', assignment].cache_key) end end def update_planner_override - return unless self.saved_change_to_workflow_state? + return unless saved_change_to_workflow_state? - if self.submission_type == "online_quiz" && self.workflow_state == "graded" + if submission_type == "online_quiz" && workflow_state == "graded" # unless it's an auto-graded quiz - return unless self.workflow_state_before_last_save == "unsubmitted" + return unless workflow_state_before_last_save == "unsubmitted" else - return unless self.workflow_state == "submitted" + return unless workflow_state == "submitted" end PlannerHelper.complete_planner_override_for_submission(self) end @@ -432,22 +432,22 @@ def new_version_needed? set_policy do given do |user| user && - user.id == self.user_id && - self.assignment.published? + user.id == user_id && + assignment.published? end can :read and can :comment and can :make_group_comment and can :submit # see user_can_read_grade? before editing :read_grade permissions given do |user| user && - user.id == self.user_id && - !self.hide_grade_from_student? + user.id == user_id && + !hide_grade_from_student? end can :read_grade given do |user, session| - self.assignment.published? && - self.assignment.context.grants_right?(user, session, :manage_grades) + assignment.published? && + assignment.context.grants_right?(user, session, :manage_grades) end can :read and can :comment and can :make_group_comment and can :read_grade and can :read_comments @@ -462,15 +462,15 @@ def new_version_needed? can :autograde given do |user, session| - self.assignment.user_can_read_grades?(user, session) + assignment.user_can_read_grades?(user, session) end can :read and can :read_grade given do |user| - self.assignment&.context && + assignment&.context && user && self.user && - self.assignment.context.observer_enrollments.where( + assignment.context.observer_enrollments.where( user_id: user, associated_user_id: self.user, workflow_state: 'active' @@ -479,12 +479,12 @@ def new_version_needed? can :read and can :read_comments given do |user| - self.assignment && - self.posted? && - self.assignment.context && + assignment && + posted? && + assignment.context && user && self.user && - self.assignment.context.observer_enrollments.where( + assignment.context.observer_enrollments.where( user_id: user, associated_user_id: self.user, workflow_state: 'active' @@ -503,7 +503,7 @@ def new_version_needed? end def observer?(user) - self.assignment.context.observer_enrollments.where( + assignment.context.observer_enrollments.where( user_id: user.id, associated_user_id: self.user.id, workflow_state: 'active' @@ -511,35 +511,35 @@ def observer?(user) end def peer_reviewer?(user) - self.assignment.published? && - self.assignment.peer_reviews && - self.assignment.context.participating_students.where(id: self.user).exists? && + assignment.published? && + assignment.peer_reviews && + assignment.context.participating_students.where(id: self.user).exists? && user && - self.assessment_requests.map(&:assessor_id).include?(user.id) + assessment_requests.map(&:assessor_id).include?(user.id) end def can_view_details?(user) return false unless grants_right?(user, :read) - return true unless self.assignment.anonymize_students? + return true unless assignment.anonymize_students? user == self.user || peer_reviewer?(user) || Account.site_admin.grants_right?(user, :update) end def can_view_plagiarism_report(type, user, session) if type == "vericite" - return false unless self.vericite_data_hash[:provider].to_s == "vericite" + return false unless vericite_data_hash[:provider].to_s == "vericite" - plagData = self.vericite_data_hash + plagData = vericite_data_hash @submit_to_vericite = false settings = assignment.vericite_settings type_can_peer_review = true else - unless self.vericite_data_hash[:provider].to_s != "vericite" || - AssignmentConfigurationToolLookup.where(assignment_id: self.assignment_id).where.not(tool_product_code: 'vericite').exists? + unless vericite_data_hash[:provider].to_s != "vericite" || + AssignmentConfigurationToolLookup.where(assignment_id: assignment_id).where.not(tool_product_code: 'vericite').exists? return false end - plagData = self.turnitin_data + plagData = turnitin_data @submit_to_turnitin = false settings = assignment.turnitin_settings type_can_peer_review = false @@ -571,26 +571,26 @@ def user_can_peer_review_plagiarism?(user) def user_can_read_grade?(user, session = nil, for_plagiarism: false) # improves performance by checking permissions on the assignment before the submission - return true if self.assignment.user_can_read_grades?(user, session) - return false if self.hide_grade_from_student?(for_plagiarism: for_plagiarism) - return true if user && user.id == self.user_id # this is fast, so skip the policy cache check if possible + return true if assignment.user_can_read_grades?(user, session) + return false if hide_grade_from_student?(for_plagiarism: for_plagiarism) + return true if user && user.id == user_id # this is fast, so skip the policy cache check if possible - self.grants_right?(user, session, :read_grade) + grants_right?(user, session, :read_grade) end on_update_send_to_streams do - if self.graded_at && self.graded_at > 5.minutes.ago && !@already_sent_to_stream + if graded_at && graded_at > 5.minutes.ago && !@already_sent_to_stream @already_sent_to_stream = true - self.user_id + user_id end end def can_read_submission_user_name?(user, session) - return false if self.user_id != user.id && self.assignment.anonymize_students? + return false if user_id != user.id && assignment.anonymize_students? - !self.assignment.anonymous_peer_reviews? || - self.user_id == user.id || - self.assignment.context.grants_right?(user, session, :view_all_grades) + !assignment.anonymous_peer_reviews? || + user_id == user.id || + assignment.context.grants_right?(user, session, :view_all_grades) end def update_final_score @@ -602,66 +602,66 @@ def update_final_score Rails.logger.debug "GRADES: submission #{global_id} score changed. recomputing grade for course #{context.global_id} user #{user_id}." self.class.connection.after_transaction_commit do Enrollment.recompute_final_score_in_singleton( - self.user_id, - self.context.id, + user_id, + context.id, grading_period_id: grading_period_id ) end end - unless ConditionalRelease::Rule.is_trigger_assignment?(self.assignment) + unless ConditionalRelease::Rule.is_trigger_assignment?(assignment) # trigger assignments have to wait for ConditionalRelease::OverrideHandler#handle_grade_change - self.assignment&.delay_if_production&.multiple_module_actions([self.user_id], :scored, self.score) + assignment&.delay_if_production&.multiple_module_actions([user_id], :scored, score) end end true end def create_alert - return unless saved_change_to_score? && self.grader_id && !self.autograded? && - self.assignment.points_possible && self.assignment.points_possible > 0 + return unless saved_change_to_score? && grader_id && !autograded? && + assignment.points_possible && assignment.points_possible > 0 - thresholds = ObserverAlertThreshold.active.where(student: self.user, + thresholds = ObserverAlertThreshold.active.where(student: user, alert_type: ['assignment_grade_high', 'assignment_grade_low']) thresholds.each do |threshold| prev_score = saved_changes['score'][0] - prev_percentage = prev_score.present? ? prev_score.to_f / self.assignment.points_possible * 100 : nil - percentage = self.score.present? ? self.score.to_f / self.assignment.points_possible * 100 : nil + prev_percentage = prev_score.present? ? prev_score.to_f / assignment.points_possible * 100 : nil + percentage = score.present? ? score.to_f / assignment.points_possible * 100 : nil next unless threshold.did_pass_threshold(prev_percentage, percentage) observer = threshold.observer next unless observer next unless observer.observer_enrollments.active - .where(course_id: self.assignment.context_id, associated_user: self.user).any? + .where(course_id: assignment.context_id, associated_user: user).any? begin ObserverAlert.create!( observer: observer, - student: self.user, + student: user, observer_alert_threshold: threshold, - context: self.assignment, + context: assignment, alert_type: threshold.alert_type, - action_date: self.graded_at, + action_date: graded_at, title: I18n.t("Assignment graded: %{grade} on %{assignment_name} in %{course_code}", { - grade: self.grade, - assignment_name: self.assignment.title, - course_code: self.assignment.course.course_code + grade: grade, + assignment_name: assignment.title, + course_code: assignment.course.course_code }) ) rescue ActiveRecord::RecordInvalid Rails.logger.error( - "Couldn't create ObserverAlert for submission #{self.id} observer #{threshold.observer_id}" + "Couldn't create ObserverAlert for submission #{id} observer #{threshold.observer_id}" ) end end end def update_quiz_submission - return true if @saved_by == :quiz_submission || !self.quiz_submission_id || self.score == self.quiz_submission.kept_score + return true if @saved_by == :quiz_submission || !quiz_submission_id || score == quiz_submission.kept_score - self.quiz_submission.set_final_score(self.score) + quiz_submission.set_final_score(score) true end @@ -675,8 +675,8 @@ def url end def plaintext_body - self.extend HtmlTextHelper - strip_tags((self.body || "").gsub(%r{<\s*br\s*/>}, "\n
").gsub(%r{

}, "

\n")) + extend HtmlTextHelper + strip_tags((body || "").gsub(%r{<\s*br\s*/>}, "\n
").gsub(%r{

}, "

\n")) end TURNITIN_STATUS_RETRY = 11 @@ -694,7 +694,7 @@ def check_turnitin_status(attempt = 1) if data[:similarity_score].blank? if attempt < TURNITIN_STATUS_RETRY - turnitin ||= Turnitin::Client.new(*self.context.turnitin_settings) + turnitin ||= Turnitin::Client.new(*context.turnitin_settings) res = turnitin.generateReport(self, asset_string) if res[:similarity_score] data[:similarity_score] = res[:similarity_score].to_f @@ -717,17 +717,17 @@ def check_turnitin_status(attempt = 1) end delay(run_at: (2**attempt).minutes.from_now).check_turnitin_status(attempt + 1) if needs_retry - self.turnitin_data_changed! - self.save + turnitin_data_changed! + save end def turnitin_report_url(asset_string, user) if self.turnitin_data && self.turnitin_data[asset_string] && self.turnitin_data[asset_string][:similarity_score] - turnitin = Turnitin::Client.new(*self.context.turnitin_settings) + turnitin = Turnitin::Client.new(*context.turnitin_settings) delay.check_turnitin_status - if self.grants_right?(user, :grade) + if grants_right?(user, :grade) turnitin.submissionReportUrl(self, asset_string) - elsif self.grants_right?(user, :view_turnitin_report) + elsif grants_right?(user, :view_turnitin_report) turnitin.submissionStudentReportUrl(self, asset_string) end else @@ -739,14 +739,14 @@ def turnitin_report_url(asset_string, user) TURNITIN_RETRY = 5 def submit_to_turnitin(attempt = 0) - return unless turnitinable? && self.context.turnitin_settings + return unless turnitinable? && context.turnitin_settings - turnitin = Turnitin::Client.new(*self.context.turnitin_settings) + turnitin = Turnitin::Client.new(*context.turnitin_settings) reset_turnitin_assets # Make sure the assignment exists and user is enrolled - assignment_created = self.assignment.create_in_turnitin - turnitin_enrollment = turnitin.enrollStudent(self.context, self.user) + assignment_created = assignment.create_in_turnitin + turnitin_enrollment = turnitin.enrollStudent(context, user) if assignment_created && turnitin_enrollment.success? delete_turnitin_errors else @@ -757,8 +757,8 @@ def submit_to_turnitin(attempt = 0) self.turnitin_data[:status] = 'error' self.turnitin_data[:assignment_error] = assignment_error if assignment_error.present? self.turnitin_data[:student_error] = turnitin_enrollment.error_hash if turnitin_enrollment.error? - self.turnitin_data_changed! - self.save + turnitin_data_changed! + save end return false end @@ -767,14 +767,14 @@ def submit_to_turnitin(attempt = 0) submission_response = turnitin.submitPaper(self) submission_response.each do |res_asset_string, response| self.turnitin_data[res_asset_string].merge!(response) - self.turnitin_data_changed! + turnitin_data_changed! if !response[:object_id] && attempt >= TURNITIN_RETRY self.turnitin_data[res_asset_string][:status] = 'error' end end delay(run_at: 5.minutes.from_now, **TURNITIN_JOB_OPTS).check_turnitin_status - self.save + save # Schedule retry if there were failures submit_status = submission_response.present? && submission_response.values.all? { |v| v[:object_id] } @@ -805,7 +805,7 @@ def originality_data end def text_entry_originality_reports - @text_entry_originality_reports ||= if self.association(:originality_reports).loaded? + @text_entry_originality_reports ||= if association(:originality_reports).loaded? originality_reports.select { |o| o.attachment_id.blank? } else originality_reports.where(attachment_id: nil) @@ -825,9 +825,9 @@ def originality_reports_for_display end def turnitin_assets - case self.submission_type + case submission_type when 'online_upload' - self.attachments.select(&:turnitinable?) + attachments.select(&:turnitinable?) when 'online_text_entry' [self] else @@ -837,7 +837,7 @@ def turnitin_assets # Preload OriginalityReport before using this method def originality_report_url(asset_string, user, attempt = nil) - return unless self.grants_right?(user, :view_turnitin_report) + return unless grants_right?(user, :view_turnitin_report) version_sub = if attempt.present? attempt.to_i == self.attempt ? self : versions.find { |v| v.model&.attempt == attempt.to_i }&.model @@ -890,22 +890,22 @@ def reset_turnitin_assets asset_data.delete(key) end self.turnitin_data[a.asset_string] = asset_data - self.turnitin_data_changed! + turnitin_data_changed! end end def resubmit_to_turnitin reset_turnitin_assets - self.save + save @submit_to_turnitin = true turnitinable_by_lti? ? retrieve_lti_tii_score : submit_to_plagiarism_later end def retrieve_lti_tii_score - if (tool = ContextExternalTool.tool_for_assignment(self.assignment)) + if (tool = ContextExternalTool.tool_for_assignment(assignment)) turnitin_data.select { |_, v| v.try(:key?, :outcome_response) }.each do |k, v| - Turnitin::OutcomeResponseProcessor.new(tool, self.assignment, self.user, v[:outcome_response].as_json).resubmit(self, k) + Turnitin::OutcomeResponseProcessor.new(tool, assignment, user, v[:outcome_response].as_json).resubmit(self, k) end end end @@ -927,7 +927,7 @@ def vericite_data(lookup_data = false) self.vericite_data_hash ||= {} # check to see if the score is stale, if so, fetch it again update_scores = false - if Canvas::Plugin.find(:vericite).try(:enabled?) && !self.readonly? && lookup_data + if Canvas::Plugin.find(:vericite).try(:enabled?) && !readonly? && lookup_data self.vericite_data_hash.each_value do |data| next unless data.is_a?(Hash) && data[:object_id] @@ -1047,11 +1047,11 @@ def check_vericite_status(attempt = 1) delay(run_at: retry_mins.minutes.from_now).check_vericite_status(attempt + 1) if attempt > 0 && needs_retry # if all we did was recheck scores, do not version this save (i.e. increase the attempt number) if data_changed - self.vericite_data_changed! + vericite_data_changed! if recheck_score_all - self.with_versioning(false, &:save!) + with_versioning(false, &:save!) else - self.save + save end end end @@ -1059,7 +1059,7 @@ def check_vericite_status(attempt = 1) def vericite_report_url(asset_string, user, session) if self.vericite_data_hash && self.vericite_data_hash[asset_string] && self.vericite_data_hash[asset_string][:similarity_score] vericite = VeriCite::Client.new - if self.grants_right?(user, :grade) + if grants_right?(user, :grade) vericite.submissionReportUrl(self, user, asset_string) elsif can_view_plagiarism_report('vericite', user, session) vericite.submissionStudentReportUrl(self, user, asset_string) @@ -1073,9 +1073,9 @@ def vericite_report_url(asset_string, user, session) VERICITE_RETRY = 5 def submit_to_vericite(attempt = 0) - Rails.logger.info("VERICITE #submit_to_vericite submission ID: #{self.id}, vericiteable? #{vericiteable?}") + Rails.logger.info("VERICITE #submit_to_vericite submission ID: #{id}, vericiteable? #{vericiteable?}") if vericiteable? - Rails.logger.info("VERICITE #submit_to_vericite submission ID: #{self.id}, plugin: #{Canvas::Plugin.find(:vericite)}, vericite plugin enabled? #{Canvas::Plugin.find(:vericite).try(:enabled?)}") + Rails.logger.info("VERICITE #submit_to_vericite submission ID: #{id}, plugin: #{Canvas::Plugin.find(:vericite)}, vericite plugin enabled? #{Canvas::Plugin.find(:vericite).try(:enabled?)}") end return unless vericiteable? && Canvas::Plugin.find(:vericite).try(:enabled?) @@ -1083,7 +1083,7 @@ def submit_to_vericite(attempt = 0) reset_vericite_assets # Make sure the assignment exists and user is enrolled - assignment_created = self.assignment.create_in_vericite + assignment_created = assignment.create_in_vericite # vericite_enrollment = vericite.enrollStudent(self.context, self.user) if assignment_created delete_vericite_errors @@ -1091,12 +1091,12 @@ def submit_to_vericite(attempt = 0) assignment_error = assignment.vericite_settings[:error] self.vericite_data_hash[:assignment_error] = assignment_error if assignment_error.present? # self.vericite_data_hash[:student_error] = vericite_enrollment.error_hash if vericite_enrollment.error? - self.vericite_data_changed! + vericite_data_changed! unless self.vericite_data_hash.empty? # only set vericite provider flag if the hash isn't empty self.vericite_data_hash[:provider] = :vericite end - self.save + save end # even if the assignment didn't save, VeriCite will still allow this file to be submitted # Submit the file(s) @@ -1108,7 +1108,7 @@ def submit_to_vericite(attempt = 0) self.vericite_data_hash[res_asset_string].merge!(response) # keep track of when we first submitted self.vericite_data_hash[res_asset_string][:submit_time] = Time.now.to_i if self.vericite_data_hash[res_asset_string][:submit_time].blank? - self.vericite_data_changed! + vericite_data_changed! if !response[:object_id] && attempt >= VERICITE_RETRY self.vericite_data_hash[res_asset_string][:status] = 'error' elsif response[:object_id] @@ -1123,7 +1123,7 @@ def submit_to_vericite(attempt = 0) # only set vericite provider flag if the hash isn't empty self.vericite_data_hash[:provider] = :vericite end - self.save + save # Schedule retry if there were failures submit_status = submission_response.present? && submission_response.values.all? { |v| v[:object_id] } @@ -1137,9 +1137,9 @@ def submit_to_vericite(attempt = 0) end def vericite_assets - case self.submission_type + case submission_type when 'online_upload' - self.attachments.select(&:vericiteable?) + attachments.select(&:vericiteable?) when 'online_text_entry' [self] else @@ -1162,7 +1162,7 @@ def reset_vericite_assets asset_data[:status] = 'pending' asset_data = clear_vericite_errors(asset_data) self.vericite_data_hash[a.asset_string] = asset_data - self.vericite_data_changed! + vericite_data_changed! end end @@ -1174,13 +1174,13 @@ def clear_vericite_errors(asset_data) end def submission_type_is_valid - case self.submission_type + case submission_type when 'online_text_entry' - if self.body.blank? + if body.blank? errors.add(:body, 'Text entry submission cannot be empty') end when 'online_url' - if self.url.blank? + if url.blank? errors.add(:url, 'URL entry submission cannot be empty') end end @@ -1194,7 +1194,7 @@ def resubmit_to_vericite end @submit_to_vericite = true - self.save + save end def vericiteable? @@ -1222,7 +1222,7 @@ def plagiarism_service_to_use # for now. @plagiarism_service_to_use = if Canvas::Plugin.find(:vericite).try(:enabled?) :vericite - elsif !self.context.turnitin_settings.nil? + elsif !context.turnitin_settings.nil? :turnitin end end @@ -1233,18 +1233,18 @@ def prep_for_submitting_to_plagiarism if plagiarism_service_to_use == :vericite plagData = self.vericite_data_hash @submit_to_vericite = false - canSubmit = self.vericiteable? + canSubmit = vericiteable? else plagData = self.turnitin_data @submit_to_turnitin = false - canSubmit = self.turnitinable? + canSubmit = turnitinable? end last_attempt = plagData && plagData[:last_processed_attempt] - Rails.logger.info("#prep_for_submitting_to_plagiarism submission ID: #{self.id}, type: #{plagiarism_service_to_use}, canSubmit? #{canSubmit}") - Rails.logger.info("#prep_for_submitting_to_plagiarism submission ID: #{self.id}, last_attempt: #{last_attempt}, self.attempt: #{self.attempt}, @group_broadcast_submission: #{@group_broadcast_submission}, self.group: #{self.group}") - if canSubmit && (!last_attempt || last_attempt < self.attempt) && (@group_broadcast_submission || !self.group) - if plagData[:last_processed_attempt] != self.attempt - plagData[:last_processed_attempt] = self.attempt + Rails.logger.info("#prep_for_submitting_to_plagiarism submission ID: #{id}, type: #{plagiarism_service_to_use}, canSubmit? #{canSubmit}") + Rails.logger.info("#prep_for_submitting_to_plagiarism submission ID: #{id}, last_attempt: #{last_attempt}, self.attempt: #{attempt}, @group_broadcast_submission: #{@group_broadcast_submission}, self.group: #{group}") + if canSubmit && (!last_attempt || last_attempt < attempt) && (@group_broadcast_submission || !group) + if plagData[:last_processed_attempt] != attempt + plagData[:last_processed_attempt] = attempt end if plagiarism_service_to_use == :vericite @submit_to_vericite = true @@ -1259,18 +1259,18 @@ def submit_to_plagiarism_later if plagiarism_service_to_use == :vericite submitPlag = @submit_to_vericite - canSubmit = self.vericiteable? + canSubmit = vericiteable? delayName = 'vericite_submission_delay_seconds' delayFunction = :submit_to_vericite delayOpts = VERICITE_JOB_OPTS else submitPlag = @submit_to_turnitin - canSubmit = self.turnitinable? + canSubmit = turnitinable? delayName = 'turnitin_submission_delay_seconds' delayFunction = :submit_to_turnitin delayOpts = TURNITIN_JOB_OPTS end - Rails.logger.info("#submit_to_plagiarism_later submission ID: #{self.id}, type: #{plagiarism_service_to_use}, canSubmit? #{canSubmit}, submitPlag? #{submitPlag}") + Rails.logger.info("#submit_to_plagiarism_later submission ID: #{id}, type: #{plagiarism_service_to_use}, canSubmit? #{canSubmit}, submitPlag? #{submitPlag}") if canSubmit && submitPlag delay = Setting.get(delayName, 60.to_s).to_i delay(run_at: delay.seconds.from_now, **delayOpts).__send__(delayFunction) @@ -1279,26 +1279,26 @@ def submit_to_plagiarism_later # End Plagiarism functions def external_tool_url - URI.encode(url) if url && self.submission_type == 'basic_lti_launch' + URI.encode(url) if url && submission_type == 'basic_lti_launch' end def clear_user_submissions_cache self.class.connection.after_transaction_commit do - User.clear_cache_keys([self.user_id], :submissions) + User.clear_cache_keys([user_id], :submissions) end end def touch_graders self.class.connection.after_transaction_commit do - if self.assignment && self.user && self.assignment.context.is_a?(Course) - self.assignment.context.clear_todo_list_cache_later(:admins) + if assignment && user && assignment.context.is_a?(Course) + assignment.context.clear_todo_list_cache_later(:admins) end end end def update_assignment unless @assignment_changed_not_sub - delay(singleton: "submission_context_module_action_#{self.global_id}", + delay(singleton: "submission_context_module_action_#{global_id}", on_conflict: :loose).context_module_action end true @@ -1306,11 +1306,11 @@ def update_assignment protected :update_assignment def context_module_action - if self.assignment && self.user - if self.score - self.assignment.context_module_action(self.user, :scored, self.score) - elsif self.submitted_at - self.assignment.context_module_action(self.user, :submitted) + if assignment && user + if score + assignment.context_module_action(user, :scored, score) + elsif submitted_at + assignment.context_module_action(user, :submitted) end end end @@ -1332,8 +1332,8 @@ def update_attachment_associations return if @assignment_changed_not_sub association_ids = attachment_associations.pluck(:attachment_id) - ids = (self.attachment_ids || "").split(",").map(&:to_i) - ids << self.attachment_id if self.attachment_id + ids = (attachment_ids || "").split(",").map(&:to_i) + ids << attachment_id if attachment_id ids.uniq! associations_to_delete = association_ids - ids attachment_associations.where(attachment_id: associations_to_delete).delete_all unless associations_to_delete.empty? @@ -1369,13 +1369,13 @@ def submit_attachments_to_canvadocs submit_to_canvadocs = true a.create_canvadoc! unless a.canvadoc a.shard.activate do - CanvadocsSubmission.find_or_create_by(submission_id: self.id, canvadoc_id: a.canvadoc.id) + CanvadocsSubmission.find_or_create_by(submission_id: id, canvadoc_id: a.canvadoc.id) end elsif a.crocodocable? submit_to_canvadocs = true a.create_crocodoc_document! unless a.crocodoc_document a.shard.activate do - CanvadocsSubmission.find_or_create_by(submission_id: self.id, crocodoc_document_id: a.crocodoc_document.id) + CanvadocsSubmission.find_or_create_by(submission_id: id, crocodoc_document_id: a.crocodoc_document.id) end end @@ -1425,35 +1425,35 @@ def infer_values end end - self.submitted_at ||= Time.now if self.has_submission? - self.quiz_submission.reload if self.quiz_submission_id - self.workflow_state = 'submitted' if self.unsubmitted? && self.submitted_at - self.workflow_state = 'unsubmitted' if self.submitted? && !self.has_submission? - self.workflow_state = 'graded' if self.grade && self.score && self.grade_matches_current_submission - self.workflow_state = 'pending_review' if self.submission_type == 'online_quiz' && self.quiz_submission.try(:latest_submitted_attempt).try(:pending_review?) - if (self.workflow_state_changed? && self.graded?) || self.late_policy_status_changed? + self.submitted_at ||= Time.now if has_submission? + quiz_submission.reload if quiz_submission_id + self.workflow_state = 'submitted' if unsubmitted? && self.submitted_at + self.workflow_state = 'unsubmitted' if submitted? && !has_submission? + self.workflow_state = 'graded' if grade && score && grade_matches_current_submission + self.workflow_state = 'pending_review' if submission_type == 'online_quiz' && quiz_submission.try(:latest_submitted_attempt).try(:pending_review?) + if (workflow_state_changed? && graded?) || late_policy_status_changed? self.graded_at = Time.now end - self.media_comment_id = nil if self.media_comment_id && self.media_comment_id.strip.empty? - if self.media_comment_id && (self.media_comment_id_changed? || !self.media_object_id) - mo = MediaObject.by_media_id(self.media_comment_id).first + self.media_comment_id = nil if media_comment_id && media_comment_id.strip.empty? + if media_comment_id && (media_comment_id_changed? || !media_object_id) + mo = MediaObject.by_media_id(media_comment_id).first self.media_object_id = mo && mo.id end - self.media_comment_type = nil unless self.media_comment_id + self.media_comment_type = nil unless media_comment_id if self.submitted_at self.attempt ||= 0 - self.attempt += 1 if self.submitted_at_changed? + self.attempt += 1 if submitted_at_changed? self.attempt = 1 if self.attempt < 1 end - if self.submission_type == 'media_recording' && !self.media_comment_id + if submission_type == 'media_recording' && !media_comment_id raise "Can't create media submission without media object" end - if self.submission_type == 'online_quiz' + if submission_type == 'online_quiz' self.quiz_submission ||= Quizzes::QuizSubmission.where(submission_id: self).first - self.quiz_submission ||= Quizzes::QuizSubmission.where(user_id: self.user_id, quiz_id: self.assignment.quiz).first rescue nil + self.quiz_submission ||= Quizzes::QuizSubmission.where(user_id: user_id, quiz_id: assignment.quiz).first rescue nil end - @just_submitted = (self.submitted? || self.pending_review?) && self.submission_type && (self.new_record? || self.workflow_state_changed? || self.attempt_changed?) + @just_submitted = (submitted? || pending_review?) && submission_type && (new_record? || workflow_state_changed? || attempt_changed?) if score_changed? || grade_changed? self.grade = if assignment assignment.score_to_grade(score, grade) @@ -1462,14 +1462,14 @@ def infer_values end end - self.grade = nil unless self.score + self.grade = nil unless score # I think the idea of having unpublished scores is unnecessarily confusing. # It may be that we want to have that functionality later on, but for now # I say it's just confusing. # if self.assignment && self.assignment.published? begin - self.published_score = self.score - self.published_grade = self.grade + self.published_score = score + self.published_grade = grade end true end @@ -1486,10 +1486,10 @@ def update_admins_if_just_submitted end def check_for_media_object - if self.media_comment_id.present? && self.saved_change_to_media_comment_id? - MediaObject.ensure_media_object(self.media_comment_id, - user: self.user, - context: self.user) + if media_comment_id.present? && saved_change_to_media_comment_id? + MediaObject.ensure_media_object(media_comment_id, + user: user, + context: user) end end @@ -1497,28 +1497,28 @@ def submission_history @submission_histories ||= begin res = [] last_submitted_at = nil - self.versions.sort_by(&:created_at).reverse_each do |version| + versions.sort_by(&:created_at).reverse_each do |version| model = version.model # since vericite_data is a function, make sure you are cloning the most recent vericite_data_hash - if self.vericiteable? - model.turnitin_data = self.vericite_data(true) + if vericiteable? + model.turnitin_data = vericite_data(true) # only use originality data if it's loaded, we want to avoid making N+1 queries - elsif self.association(:originality_reports).loaded? - model.turnitin_data = self.originality_data + elsif association(:originality_reports).loaded? + model.turnitin_data = originality_data end if model.submitted_at && last_submitted_at.to_i != model.submitted_at.to_i res << model last_submitted_at = model.submitted_at end end - res = self.versions.to_a[0, 1].map(&:model) if res.empty? + res = versions.to_a[0, 1].map(&:model) if res.empty? res = [self] if res.empty? res.sort_by { |s| s.submitted_at || CanvasSort::First } end end def check_is_new_attempt - @attempt_changed = self.attempt_changed? + @attempt_changed = attempt_changed? true end @@ -1559,7 +1559,7 @@ def submitted_to_lti_assignment?(assignment_submitted_to) private :submitted_to_lti_assignment? def score_missing(late_policy, points_possible, grading_type) - if self.points_deducted.present? + if points_deducted.present? self.score = entered_score unless score_changed? self.points_deducted = nil end @@ -1641,9 +1641,9 @@ def extra_attempts_can_only_be_set_on_online_uploads end def attempts_left - return nil if self.assignment.allowed_attempts.nil? || self.assignment.allowed_attempts < 0 + return nil if assignment.allowed_attempts.nil? || assignment.allowed_attempts < 0 - [0, self.assignment.allowed_attempts + (self.extra_attempts || 0) - (self.attempt || 0)].max + [0, assignment.allowed_attempts + (extra_attempts || 0) - (self.attempt || 0)].max end def ensure_attempts_are_in_range @@ -1708,7 +1708,7 @@ def can_grade_symbolic_status(user = nil) private :can_grade_symbolic_status def queue_websnap - if !self.attachment_id && @attempt_changed && self.url && self.submission_type == 'online_url' + if !attachment_id && @attempt_changed && url && submission_type == 'online_url' delay(priority: Delayed::LOW_PRIORITY).get_web_snapshot end end @@ -1726,7 +1726,7 @@ def versioned_originality_reports attachment_ids = attachment_ids_for_version if attachment_ids.empty? [] - elsif self.association(:originality_reports).loaded? + elsif association(:originality_reports).loaded? originality_reports.select { |o| attachment_ids.include?(o.attachment_id) } else originality_reports.where(attachment_id: attachment_ids) @@ -1841,11 +1841,11 @@ def self.bulk_load_attachments_for_submissions(submissions, preloads: nil) end def includes_attachment?(attachment) - self.versions.map(&:model).any? { |v| (v.attachment_ids || "").split(',').map(&:to_i).include?(attachment.id) } + versions.map(&:model).any? { |v| (v.attachment_ids || "").split(',').map(&:to_i).include?(attachment.id) } end def <=>(other) - self.updated_at <=> other.updated_at + updated_at <=> other.updated_at end def course_broadcast_data @@ -1919,19 +1919,19 @@ def assignment_graded_in_the_last_hour? end def teacher - @teacher ||= self.assignment.teacher_enrollment.user + @teacher ||= assignment.teacher_enrollment.user end def update_if_pending @attachments = nil - if self.submission_type == 'online_quiz' && self.quiz_submission_id && self.score && self.score == self.quiz_submission.score + if submission_type == 'online_quiz' && quiz_submission_id && score && score == self.quiz_submission.score self.workflow_state = self.quiz_submission.complete? ? 'graded' : 'pending_review' end true end def attachments - Attachment.where(:id => self.attachment_associations.pluck(:attachment_id)) + Attachment.where(:id => attachment_associations.pluck(:attachment_id)) end def attachments=(attachments) @@ -1940,8 +1940,8 @@ def attachments=(attachments) # one student from sneakily getting access to files in another user's comments, # since they're all being held on the assignment for now. attachments ||= [] - old_ids = (Array(self.attachment_ids || "").join(",")).split(",").map(&:to_i) - write_attribute(:attachment_ids, attachments.select { |a| (a && a.id && old_ids.include?(a.id)) || (a.recently_created? && a.context == self.assignment) || a.context != self.assignment }.map(&:id).join(",")) + old_ids = (Array(attachment_ids || "").join(",")).split(",").map(&:to_i) + write_attribute(:attachment_ids, attachments.select { |a| (a && a.id && old_ids.include?(a.id)) || (a.recently_created? && a.context == assignment) || a.context != assignment }.map(&:id).join(",")) end # someday code-archaeologists will wonder how this method came to be named @@ -1953,17 +1953,17 @@ def validate_single_submission self.url = read_attribute(:url)[0..250] end unless submission_type - self.submission_type ||= "online_url" if self.url - self.submission_type ||= "online_text_entry" if self.body - self.submission_type ||= "online_upload" unless self.attachment_ids.blank? + self.submission_type ||= "online_url" if url + self.submission_type ||= "online_text_entry" if body + self.submission_type ||= "online_upload" unless attachment_ids.blank? end true end private :validate_single_submission - def grade_change_audit(force_audit: self.assignment_changed_not_sub, skip_insert: false) - newly_graded = self.saved_change_to_workflow_state? && self.workflow_state == 'graded' - grade_changed = (self.saved_changes.keys & %w[grade score excused]).present? + def grade_change_audit(force_audit: assignment_changed_not_sub, skip_insert: false) + newly_graded = saved_change_to_workflow_state? && workflow_state == 'graded' + grade_changed = (saved_changes.keys & %w[grade score excused]).present? return true unless newly_graded || grade_changed || force_audit if grade_change_event_author_id.present? @@ -1976,18 +1976,18 @@ def grade_change_audit(force_audit: self.assignment_changed_not_sub, skip_insert end def queue_conditional_release_grade_change_handler - self.shard.activate do - return unless self.graded? && self.posted? + shard.activate do + return unless graded? && posted? # use request caches to handle n+1's when updating a lot of submissions in the same course in one request - return unless RequestCache.cache('conditional_release_feature_enabled', self.course_id) do - self.course.feature_enabled?(:conditional_release) + return unless RequestCache.cache('conditional_release_feature_enabled', course_id) do + course.feature_enabled?(:conditional_release) end - if ConditionalRelease::Rule.is_trigger_assignment?(self.assignment) - strand = "conditional_release_grade_change:#{self.global_assignment_id}" + if ConditionalRelease::Rule.is_trigger_assignment?(assignment) + strand = "conditional_release_grade_change:#{global_assignment_id}" ConditionalRelease::OverrideHandler.delay_if_production(priority: Delayed::LOW_PRIORITY, strand: strand) .handle_grade_change(self) - self.assignment&.delay_if_production(strand: strand)&.multiple_module_actions([self.user_id], :scored, self.score) + assignment&.delay_if_production(strand: strand)&.multiple_module_actions([user_id], :scored, score) end end end @@ -2037,9 +2037,9 @@ def readable_state end def grading_type - return nil unless self.assignment + return nil unless assignment - self.assignment.grading_type + assignment.grading_type end def last_teacher_comment @@ -2084,7 +2084,7 @@ def processed? def provisional_grade(scorer, final: false, preloaded_grades: nil, default_to_null_grade: true) pg = if preloaded_grades - pgs = preloaded_grades[self.id] || [] + pgs = preloaded_grades[id] || [] if final pgs.detect(&:final) else @@ -2092,9 +2092,9 @@ def provisional_grade(scorer, final: false, preloaded_grades: nil, default_to_nu end else if final - self.provisional_grades.final.first + provisional_grades.final.first else - self.provisional_grades.not_final.where(scorer_id: scorer).first + provisional_grades.not_final.where(scorer_id: scorer).first end end @@ -2107,11 +2107,11 @@ def provisional_grade(scorer, final: false, preloaded_grades: nil, default_to_nu def find_or_create_provisional_grade!(scorer, attrs = {}) ModeratedGrading::ProvisionalGrade.unique_constraint_retry do - if attrs[:final] && !self.assignment.permits_moderation?(scorer) + if attrs[:final] && !assignment.permits_moderation?(scorer) raise Assignment::GradeError, 'User not authorized to give final provisional grades' end - pg = find_existing_provisional_grade(scorer, attrs[:final]) || self.provisional_grades.build + pg = find_existing_provisional_grade(scorer, attrs[:final]) || provisional_grades.build pg = update_provisional_grade(pg, scorer, attrs) pg.save! if attrs[:force_save] || pg.new_record? || pg.changed? pg @@ -2119,10 +2119,10 @@ def find_or_create_provisional_grade!(scorer, attrs = {}) end def find_existing_provisional_grade(scorer, final) - final ? self.provisional_grades.final.first : self.provisional_grades.not_final.find_by(scorer: scorer) + final ? provisional_grades.final.first : provisional_grades.not_final.find_by(scorer: scorer) end - def moderated_grading_allow_list(current_user = self.user, loaded_attachments: nil) + def moderated_grading_allow_list(current_user = user, loaded_attachments: nil) return nil unless assignment.moderated_grading? && current_user.present? has_crocodoc = (loaded_attachments || attachments).any?(&:crocodoc_available?) @@ -2137,23 +2137,23 @@ def moderation_allow_list_for_user(current_user) if assignment.annotated_document? # The student's annotations are what make up the submission in this case. - allow_list.push(self.user) + allow_list.push(user) end if posted? - allow_list.push(self.grader, self.user, current_user) - elsif self.user == current_user + allow_list.push(grader, user, current_user) + elsif user == current_user # Requesting user is the student. allow_list << current_user elsif assignment.permits_moderation?(current_user) # Requesting user is the final grader or an administrator. - allow_list.push(*assignment.moderation_grader_users_with_slot_taken, self.user, current_user) + allow_list.push(*assignment.moderation_grader_users_with_slot_taken, user, current_user) elsif assignment.can_be_moderated_grader?(current_user) # Requesting user is a provisional grader, or eligible to be one. if assignment.grader_comments_visible_to_graders - allow_list.push(*assignment.moderation_grader_users_with_slot_taken, self.user, current_user) + allow_list.push(*assignment.moderation_grader_users_with_slot_taken, user, current_user) else - allow_list.push(current_user, self.user) + allow_list.push(current_user, user) end end allow_list.compact.uniq @@ -2167,7 +2167,7 @@ def anonymous_identities def add_comment(opts = {}) opts = opts.symbolize_keys - opts[:author] ||= opts[:commenter] || opts[:author] || opts[:user] || self.user unless opts[:skip_author] + opts[:author] ||= opts[:commenter] || opts[:author] || opts[:user] || user unless opts[:skip_author] opts[:comment] = opts[:comment].try(:strip) || "" opts[:attachments] ||= opts[:comment_attachments] opts[:draft] = !!opts[:draft_comment] @@ -2183,13 +2183,13 @@ def add_comment(opts = {}) opts[:provisional_grade_id] = pg.id end - if self.new_record? - self.save! + if new_record? + save! elsif comment_causes_posting?(author: opts[:author], draft: opts[:draft], provisional: opts[:provisional]) opts[:hidden] = false update!(posted_at: Time.zone.now) else - self.touch + touch end valid_keys = [:comment, :author, :media_comment_id, :media_comment_type, :group_comment_id, :assessment_request, :attachments, @@ -2229,7 +2229,7 @@ def apply_provisional_grade_filter!(provisional_grade) self.score = provisional_grade.score self.graded_at = provisional_grade.graded_at self.grade_matches_current_submission = provisional_grade.grade_matches_current_submission - self.readonly! + readonly! end def provisional_grade_id @@ -2287,17 +2287,17 @@ def visible_submission_comments_for(current_user) # comments prior to first attempt will count as current until a second attempt is started def feedback_for_current_attempt? visible_submission_comments.any? do |comment| - comment.author_id != self.user_id && + comment.author_id != user_id && ((comment.attempt&.nonzero? ? comment.attempt : 1) == (self.attempt || 1)) end end def assessment_request_count - @assessment_requests_count ||= self.assessment_requests.length + @assessment_requests_count ||= assessment_requests.length end def assigned_assessment_count - @assigned_assessment_count ||= self.assigned_assessments.length + @assigned_assessment_count ||= assigned_assessments.length end def assign_assessment(obj) @@ -2312,10 +2312,10 @@ def assign_assessor(obj) @assessment_request_count ||= 0 @assessment_request_count += 1 user = obj.user rescue nil - association = self.assignment.active_rubric_association? ? self.assignment.rubric_association : nil - res = self.assessment_requests.where(assessor_asset_id: obj.id, assessor_asset_type: obj.class.to_s, assessor_id: user.id, rubric_association_id: association.try(:id)) - .first_or_initialize - res.user_id = self.user_id + association = assignment.active_rubric_association? ? assignment.rubric_association : nil + res = assessment_requests.where(assessor_asset_id: obj.id, assessor_asset_type: obj.class.to_s, assessor_id: user.id, rubric_association_id: association.try(:id)) + .first_or_initialize + res.user_id = user_id res.workflow_state = 'assigned' if res.new_record? just_created = res.new_record? res.send_reminder! # this method also saves the assessment_request @@ -2324,12 +2324,12 @@ def assign_assessor(obj) end def students - self.group ? self.group.users : [self.user] + group ? group.users : [user] end def broadcast_group_submission @group_broadcast_submission = true - self.save! + save! @group_broadcast_submission = false end @@ -2383,7 +2383,7 @@ def seconds_late def time_of_submission time = submitted_at || Time.zone.now - time -= 60.seconds if submission_type == 'online_quiz' || self.assignment.quiz_lti? + time -= 60.seconds if submission_type == 'online_quiz' || assignment.quiz_lti? time end private :time_of_submission @@ -2391,22 +2391,22 @@ def time_of_submission include Tardiness def current_submission_graded? - self.graded? && (!self.submitted_at || (self.graded_at && self.graded_at >= self.submitted_at)) + graded? && (!self.submitted_at || (graded_at && graded_at >= self.submitted_at)) end def context - self.course ||= self.assignment&.context + self.course ||= assignment&.context end def to_atom(opts = {}) - author_name = self.assignment.present? && self.assignment.context.present? ? self.assignment.context.name : t('atom_no_author', "No Author") + author_name = assignment.present? && assignment.context.present? ? assignment.context.name : t('atom_no_author', "No Author") Atom::Entry.new do |entry| - entry.title = "#{user.name} -- #{assignment.title}#{', ' + self.assignment.context.name if opts[:include_context]}" - entry.updated = self.updated_at - entry.published = self.created_at - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime('%Y-%m-%d')}:/submissions/#{self.feed_code}_#{self.updated_at.strftime('%Y-%m-%d')}" - entry.content = Atom::Content::Html.new(self.body || "") - entry.links << Atom::Link.new(:rel => 'alternate', :href => "#{self.assignment.direct_link}/submissions/#{self.id}") + entry.title = "#{user.name} -- #{assignment.title}#{', ' + assignment.context.name if opts[:include_context]}" + entry.updated = updated_at + entry.published = created_at + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime('%Y-%m-%d')}:/submissions/#{feed_code}_#{updated_at.strftime('%Y-%m-%d')}" + entry.content = Atom::Content::Html.new(body || "") + entry.links << Atom::Link.new(:rel => 'alternate', :href => "#{assignment.direct_link}/submissions/#{id}") entry.authors << Atom::Person.new(:name => author_name) # entry.author = Atom::Person.new(self.user) end @@ -2462,19 +2462,19 @@ def get_web_snapshot # This should always be called in the context of a delayed job return unless CutyCapt.enabled? - if (attachment = CutyCapt.snapshot_attachment_for_url(self.url)) + if (attachment = CutyCapt.snapshot_attachment_for_url(url)) attachment.context = self attachment.save! attach_screenshot(attachment) else - logger.error("Error capturing web snapshot for submission #{self.global_id}") + logger.error("Error capturing web snapshot for submission #{global_id}") end end def attach_screenshot(attachment) self.attachment = attachment self.processed = true - self.save! + save! end def excused=(excused) @@ -2505,15 +2505,15 @@ def filter_attributes_for_user(hash, user, session) def update_participation # TODO: can we do this in bulk? return if assignment.deleted? || assignment.muted? - return unless self.user_id + return unless user_id return unless saved_change_to_score? || saved_change_to_grade? || saved_change_to_excused? - return unless self.context.grants_right?(self.user, :participate_as_student) + return unless context.grants_right?(user, :participate_as_student) ContentParticipation.create_or_update({ :content => self, - :user => self.user, + :user => user, :workflow_state => "unread", }) end @@ -2537,11 +2537,11 @@ def delete_ignores end def delete_submission_drafts! - self.submission_drafts.destroy_all + submission_drafts.destroy_all end def point_data? - !!(self.score || self.grade) + !!(score || grade) end def read_state(current_user) @@ -2554,8 +2554,8 @@ def read_state(current_user) content_participations.where(user_id: uid).pick(:workflow_state) end return state if state.present? - return "read" if assignment.deleted? || assignment.muted? || !self.user_id - return "unread" if self.grade || self.score + return "read" if assignment.deleted? || assignment.muted? || !user_id + return "unread" if grade || score has_comments = if visible_submission_comments.loaded? visible_submission_comments.detect { |c| c.author_id != user_id } @@ -2585,7 +2585,7 @@ def mark_unread(current_user) def change_read_state(new_state, current_user) return nil unless current_user - return true if new_state == self.read_state(current_user) + return true if new_state == read_state(current_user) StreamItem.update_read_state_for_asset(self, new_state, current_user.id) PlannerHelper.clear_planner_cache(current_user) @@ -2606,7 +2606,7 @@ def mute end def muted_assignment? - self.assignment.muted? + assignment.muted? end def hide_grade_from_student?(for_plagiarism: false) @@ -2634,11 +2634,11 @@ def posted? end def assignment_muted_changed - self.grade_change_audit(force_audit: true, skip_insert: true) + grade_change_audit(force_audit: true, skip_insert: true) end def without_graded_submission? - !self.has_submission? && !self.graded? + !has_submission? && !graded? end def visible_rubric_assessments_for(viewing_user, attempt: nil) @@ -2654,7 +2654,7 @@ def visible_rubric_assessments_for(viewing_user, attempt: nil) filtered_assessments = rubric_assessments_for_attempt(attempt: attempt).select do |a| a.grants_right?(viewing_user, :read) && - a.rubric_association == self.assignment.rubric_association + a.rubric_association == assignment.rubric_association end filtered_assessments.sort_by do |a| [ @@ -2848,7 +2848,7 @@ def set_late_policy_attributes end def reset_redo_request - self.redo_request = false if self.redo_request && self.attempt_changed? + self.redo_request = false if redo_request && attempt_changed? end def set_root_account_id @@ -2920,10 +2920,10 @@ def handle_posted_at_changed # posting/hiding on a separate copy of the assignment, then reload our copy # of the assignment to make sure we pick up any changes to the muted status. if posted? && !previously_posted - Assignment.find(assignment_id).post_submissions(submission_ids: [self.id], skip_updating_timestamp: true) + Assignment.find(assignment_id).post_submissions(submission_ids: [id], skip_updating_timestamp: true) assignment.reload elsif !posted? && previously_posted - Assignment.find(assignment_id).hide_submissions(submission_ids: [self.id], skip_updating_timestamp: true) + Assignment.find(assignment_id).hide_submissions(submission_ids: [id], skip_updating_timestamp: true) assignment.reload end end diff --git a/app/models/submission_comment.rb b/app/models/submission_comment.rb index a750c5c04866c..b1065fa618bfb 100644 --- a/app/models/submission_comment.rb +++ b/app/models/submission_comment.rb @@ -137,38 +137,38 @@ def post_submission_for_finalized_draft has_a_broadcast_policy def provisional - !!self.provisional_grade_id + !!provisional_grade_id end def read?(current_user) - self.submission.read?(current_user) || self.viewed_submission_comments.where(user: current_user).exists? + submission.read?(current_user) || viewed_submission_comments.where(user: current_user).exists? end def mark_read!(current_user) ViewedSubmissionComment.unique_constraint_retry do - self.viewed_submission_comments.where(user: current_user).first_or_create! + viewed_submission_comments.where(user: current_user).first_or_create! end end def media_comment? - self.media_comment_id && self.media_comment_type + media_comment_id && media_comment_type end def check_for_media_object - if self.media_comment? && self.saved_change_to_media_comment_id? - MediaObject.ensure_media_object(self.media_comment_id, - user: self.author, - context: self.author) + if media_comment? && saved_change_to_media_comment_id? + MediaObject.ensure_media_object(media_comment_id, + user: author, + context: author) end end on_create_send_to_streams do - if self.submission && self.provisional_grade_id.nil? - if self.author_id == self.submission.user_id - self.submission.context.instructors_in_charge_of(self.author_id) + if submission && provisional_grade_id.nil? + if author_id == submission.user_id + submission.context.instructors_in_charge_of(author_id) else # self.submission.context.instructors.map(&:id) + [self.submission.user_id] - [self.author_id] - self.submission.user_id + submission.user_id end end end @@ -177,14 +177,14 @@ def check_for_media_object given { |user, session| can_view_comment?(user, session) } can :read - given { |user| self.author == user } + given { |user| author == user } can :read and can :delete and can :update given { |user, session| submission.grants_right?(user, session, :grade) } can :delete given { |user, session| - self.can_read_author?(user, session) + can_read_author?(user, session) } can :read_author end @@ -281,40 +281,40 @@ def can_view_comment?(user, session) def can_read_author?(user, session) RequestCache.cache('user_can_read_author', self, user, session) do - return false if user.nil? || (self.author_id != user.id && self.submission.assignment.anonymize_students?) + return false if user.nil? || (author_id != user.id && submission.assignment.anonymize_students?) - self.author_id == user.id || - (!self.anonymous? && !self.submission.assignment.anonymous_peer_reviews?) || - self.submission.assignment.context.grants_right?(user, session, :view_all_grades) || - self.submission.assignment.context.grants_right?(self.author, session, :view_all_grades) + author_id == user.id || + (!anonymous? && !submission.assignment.anonymous_peer_reviews?) || + submission.assignment.context.grants_right?(user, session, :view_all_grades) || + submission.assignment.context.grants_right?(author, session, :view_all_grades) end end def reply_from(opts) - raise IncomingMail::Errors::UnknownAddress if self.context.root_account.deleted? + raise IncomingMail::Errors::UnknownAddress if context.root_account.deleted? user = opts[:user] message = opts[:text].strip - user = nil unless user && self.submission.grants_right?(user, :comment) + user = nil unless user && submission.grants_right?(user, :comment) if !user raise IncomingMail::Errors::InvalidParticipant else - self.shard.activate do - self.submission.add_comment( + shard.activate do + submission.add_comment( author: user, comment: message, - provisional: self.provisional_grade_id.present? + provisional: provisional_grade_id.present? ) end end end def context - read_attribute(:context) || self.submission.assignment.context rescue nil + read_attribute(:context) || submission.assignment.context rescue nil end def parse_attachment_ids - (self.attachment_ids || "").split(",").map(&:to_i) + (attachment_ids || "").split(",").map(&:to_i) end def attachment_ids=(ids) @@ -336,10 +336,10 @@ def attachments=(attachments) end def infer_details - self.anonymous = self.submission.assignment.anonymous_peer_reviews - self.author_name ||= self.author.short_name rescue t(:unknown_author, "Someone") - self.cached_attachments = self.attachments.map { |a| OpenObject.build('attachment', a.attributes) } - self.context = self.read_attribute(:context) || self.submission.assignment.context rescue nil + self.anonymous = submission.assignment.anonymous_peer_reviews + self.author_name ||= author.short_name rescue t(:unknown_author, "Someone") + self.cached_attachments = attachments.map { |a| OpenObject.build('attachment', a.attributes) } + self.context = read_attribute(:context) || submission.assignment.context rescue nil self.workflow_state ||= "active" end @@ -349,8 +349,8 @@ def set_root_account_id end def force_reload_cached_attachments - self.cached_attachments = self.attachments.map { |a| OpenObject.build('attachment', a.attributes) } - self.save + self.cached_attachments = attachments.map { |a| OpenObject.build('attachment', a.attributes) } + save end def attachments @@ -390,11 +390,11 @@ def formatted_body(truncate = nil) end def context_code - "#{self.context_type.downcase}_#{self.context_id}" + "#{context_type.downcase}_#{context_id}" end def avatar_path - "/images/users/#{User.avatar_key(self.author_id)}" + "/images/users/#{User.avatar_key(author_id)}" end def serialization_methods diff --git a/app/models/submission_draft.rb b/app/models/submission_draft.rb index 01f9f28dc1603..e2f208354ef15 100644 --- a/app/models/submission_draft.rb +++ b/app/models/submission_draft.rb @@ -39,12 +39,12 @@ class SubmissionDraft < ActiveRecord::Base before_save :validate_lti_launch_url def validate_url - if self.url.present? + if url.present? begin # also updates the url with a scheme if missing and is a valid url # otherwise leaves the url as whatever the user submitted as thier draft - value, = CanvasHttp.validate_url(self.url) - self.send("url=", value) + value, = CanvasHttp.validate_url(url) + send("url=", value) rescue nil end @@ -55,13 +55,13 @@ def validate_lti_launch_url return if lti_launch_url.blank? value, = CanvasHttp.validate_url(lti_launch_url) - self.send("lti_launch_url=", value) if value + send("lti_launch_url=", value) if value rescue # we couldn't validate, just leave it end def media_object_id_matches_media_object - if self.media_object_id.present? && self.media_object.blank? + if media_object_id.present? && media_object.blank? err = I18n.t('the media_object_id must match an existing media object') errors.add(:media_object_id, err) end @@ -69,8 +69,8 @@ def media_object_id_matches_media_object private :media_object_id_matches_media_object def submission_attempt_matches_submission - current_submission_attempt = self.submission&.attempt || 0 - this_submission_attempt = self.submission_attempt || 0 + current_submission_attempt = submission&.attempt || 0 + this_submission_attempt = submission_attempt || 0 if this_submission_attempt > (current_submission_attempt + 1) err = I18n.t('submission draft cannot be more then one attempt ahead of the current submission') errors.add(:submission_draft_attempt, err) @@ -79,22 +79,22 @@ def submission_attempt_matches_submission private :submission_attempt_matches_submission def meets_media_recording_criteria? - self.media_object_id.present? + media_object_id.present? end def meets_text_entry_criteria? - self.body.present? + body.present? end def meets_upload_criteria? - self.attachments.present? + attachments.present? end def meets_url_criteria? - return false if self.url.blank? + return false if url.blank? begin - CanvasHttp.validate_url(self.url) + CanvasHttp.validate_url(url) true rescue false @@ -102,7 +102,7 @@ def meets_url_criteria? end def meets_student_annotation_criteria? - self.submission.annotation_context(in_progress: true).present? + submission.annotation_context(in_progress: true).present? end def meets_basic_lti_launch_criteria? @@ -118,7 +118,7 @@ def meets_basic_lti_launch_criteria? # this checks if any type on the assignment is drafted def meets_assignment_criteria? - submission_types = self.submission.assignment.submission_types.split(',') + submission_types = submission.assignment.submission_types.split(',') submission_types.each do |type| case type when 'media_recording' diff --git a/app/models/terms_of_service.rb b/app/models/terms_of_service.rb index 6586bbe40622d..6154236f02bcf 100644 --- a/app/models/terms_of_service.rb +++ b/app/models/terms_of_service.rb @@ -31,24 +31,24 @@ class TermsOfService < ActiveRecord::Base cattr_accessor :skip_automatic_terms_creation def validate_account_is_root - if self.account_id_changed? && !self.account.root_account? - self.errors.add(:account, "must be root account") + if account_id_changed? && !account.root_account? + errors.add(:account, "must be root account") end end def set_content_on_type_change - self.terms_of_service_content = self.custom? ? self.account.terms_of_service_content : nil + self.terms_of_service_content = custom? ? account.terms_of_service_content : nil end def custom? - self.terms_type == "custom" + terms_type == "custom" end def self.ensure_terms_for_account(account, is_new_account = false) - return unless self.table_exists? + return unless table_exists? passive = is_new_account || !(Setting.get('terms_required', 'true') == 'true' && account.account_terms_required?) - self.unique_constraint_retry do |retry_count| + unique_constraint_retry do |retry_count| account.reload_terms_of_service if retry_count > 0 account.terms_of_service || account.create_terms_of_service!(term_options_for_account(account).merge(:passive => passive)) end @@ -60,7 +60,7 @@ def self.term_options_for_account(_account) end def self.type_dropdown_options_for_account(_account = nil) - self.type_dropdown_options + type_dropdown_options end def self.type_dropdown_options diff --git a/app/models/terms_of_service_content.rb b/app/models/terms_of_service_content.rb index f39bda68e6794..b00c72aa48f38 100644 --- a/app/models/terms_of_service_content.rb +++ b/app/models/terms_of_service_content.rb @@ -34,11 +34,11 @@ def ensure_terms_updated_at end def set_terms_updated_at - self.terms_updated_at = Time.now.utc if self.content_changed? + self.terms_updated_at = Time.now.utc if content_changed? end def self.ensure_content_for_account(account) - self.unique_constraint_retry do |retry_count| + unique_constraint_retry do |retry_count| account.reload_terms_of_service_content if retry_count > 0 account.terms_of_service_content || account.create_terms_of_service_content!(content: "") end diff --git a/app/models/thumbnail.rb b/app/models/thumbnail.rb index 7cb1b458c517f..51ec7e54214b4 100644 --- a/app/models/thumbnail.rb +++ b/app/models/thumbnail.rb @@ -43,9 +43,7 @@ def local_storage_path "#{HostUrl.context_host(attachment.context)}/images/thumbnails/show/#{id}/#{uuid}" end - def bucket - self.attachment.bucket - end + delegate :bucket, to: :attachment def cached_s3_url @cached_s3_url = authenticated_s3_url(expires_in: 144.hours) diff --git a/app/models/user.rb b/app/models/user.rb index 4810f89d4b4f7..463f453fe4ebf 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -261,7 +261,7 @@ def page_views(options = {}) end scopes.map!(&:to_sql) - self.from("(#{scopes.join("\nUNION\n")}) users") + from("(#{scopes.join("\nUNION\n")}) users") } scope :active, -> { where("users.workflow_state<>'deleted'") } @@ -329,9 +329,9 @@ def self.public_lti_id def self.order_by_sortable_name(options = {}) clause = sortable_name_order_by_clause sort_direction = options[:direction] == :descending ? 'DESC' : 'ASC' - scope = self.order(Arel.sql("#{clause} #{sort_direction}")).order(Arel.sql("#{self.table_name}.id #{sort_direction}")) + scope = order(Arel.sql("#{clause} #{sort_direction}")).order(Arel.sql("#{table_name}.id #{sort_direction}")) if scope.select_values.empty? - scope = scope.select(self.arel_table[Arel.star]) + scope = scope.select(arel_table[Arel.star]) end if scope.select_values.present? scope = scope.select(clause) @@ -343,7 +343,7 @@ def self.order_by_sortable_name(options = {}) end def self.by_top_enrollment - scope = self.all + scope = all if scope.select_values.blank? scope = scope.select("users.*") end @@ -425,12 +425,12 @@ def self.preload_last_login(users, account_id) after_save :self_enroll_if_necessary def courses_for_enrollments(enrollment_scope, associated_user = nil) - if associated_user && associated_user != self.id + if associated_user && associated_user != id Course.active.joins(:observer_enrollments) .merge(enrollment_scope.except(:joins)) .where(enrollments: { associated_user_id: associated_user }) else - enrollments_to_include = associated_user == self.id ? :non_observer_enrollments : :all_enrollments + enrollments_to_include = associated_user == id ? :non_observer_enrollments : :all_enrollments Course.active.joins(enrollments_to_include).merge(enrollment_scope.except(:joins)).distinct end end @@ -472,8 +472,8 @@ def update_root_account_ids refreshed_root_account_ids = Set.new Shard.with_each_shard(shards) do - UserAccountAssociation.for_root_accounts.for_user_id(self.id).each do |uaa| - refreshed_root_account_ids << Shard.relative_id_for(uaa.account_id, Shard.current, self.shard) + UserAccountAssociation.for_root_accounts.for_user_id(id).each do |uaa| + refreshed_root_account_ids << Shard.relative_id_for(uaa.account_id, Shard.current, shard) end end @@ -482,7 +482,7 @@ def update_root_account_ids if root_account_ids_changed? save! # Update each communication channel associated with the user - self.communication_channels.update_all(root_account_ids: self.root_account_ids) + communication_channels.update_all(root_account_ids: root_account_ids) end end @@ -495,7 +495,7 @@ def update_account_associations_later end def update_account_associations_if_necessary - update_account_associations if !self.class.skip_updating_account_associations? && self.saved_change_to_workflow_state? && self.id_before_last_save + update_account_associations if !self.class.skip_updating_account_associations? && saved_change_to_workflow_state? && id_before_last_save end def update_account_associations(opts = nil) @@ -503,7 +503,7 @@ def update_account_associations(opts = nil) # incremental is only for the current shard return User.update_account_associations([self], opts) if opts[:incremental] - self.shard.activate do + shard.activate do User.update_account_associations([self], opts) end end @@ -761,11 +761,11 @@ def group_memberships_for(context) # Returns an array of groups which are currently visible for the user. def visible_groups - @visible_groups ||= filter_visible_groups_for_user(self.current_groups) + @visible_groups ||= filter_visible_groups_for_user(current_groups) end def filter_visible_groups_for_user(groups) - enrollments = self.cached_currentish_enrollments(preload_dates: true, preload_courses: true) + enrollments = cached_currentish_enrollments(preload_dates: true, preload_courses: true) groups.select do |group| group.context_type != 'Course' || enrollments.any? do |en| en.course == group.context && !(en.inactive? || en.completed?) && (en.admin? || en.course.available?) @@ -774,7 +774,7 @@ def filter_visible_groups_for_user(groups) end def <=>(other) - self.name <=> other.name + name <=> other.name end def available? @@ -787,7 +787,7 @@ def participants # compatibility only - this isn't really last_name_first def last_name_first - self.sortable_name + sortable_name end def last_name_first_or_unnamed @@ -797,11 +797,11 @@ def last_name_first_or_unnamed end def first_name - User.name_parts(self.sortable_name, likely_already_surname_first: true)[0] || '' + User.name_parts(sortable_name, likely_already_surname_first: true)[0] || '' end def last_name - User.name_parts(self.sortable_name, likely_already_surname_first: true)[1] || '' + User.name_parts(sortable_name, likely_already_surname_first: true)[1] || '' end # Feel free to add, but the "authoritative" list (http://en.wikipedia.org/wiki/Title_(name)) is quite large @@ -855,18 +855,18 @@ def self.last_name_first(name, name_was = nil, likely_already_surname_first:) end def infer_defaults - self.name = nil if self.name == "User" - self.name ||= self.email || t('#user.default_user_name', "User") - self.short_name = nil if self.short_name == "" + self.name = nil if name == "User" + self.name ||= email || t('#user.default_user_name', "User") + self.short_name = nil if short_name == "" self.short_name ||= self.name - self.sortable_name = nil if self.sortable_name == "" + self.sortable_name = nil if sortable_name == "" # recalculate the sortable name if the name changed, but the sortable name didn't, and the sortable_name matches the old name - self.sortable_name = nil if !self.sortable_name_changed? && + self.sortable_name = nil if !sortable_name_changed? && !sortable_name_explicitly_set && - self.name_changed? && - User.name_parts(self.sortable_name, likely_already_surname_first: true).compact.join(' ') == self.name_was + name_changed? && + User.name_parts(sortable_name, likely_already_surname_first: true).compact.join(' ') == name_was unless read_attribute(:sortable_name) - self.sortable_name = User.last_name_first(self.name, self.sortable_name_was, likely_already_surname_first: true) + self.sortable_name = User.last_name_first(self.name, sortable_name_was, likely_already_surname_first: true) end self.reminder_time_for_due_dates ||= 48.hours.to_i self.reminder_time_for_grading ||= 0 @@ -879,7 +879,7 @@ def infer_defaults # which also depends on the current context. def lookup_lti_id(context) old_lti_id = context.shard.activate do - self.past_lti_ids.where(context: context).take&.user_lti_id + past_lti_ids.where(context: context).take&.user_lti_id end old_lti_id || self.lti_id end @@ -893,7 +893,7 @@ def ensure_lti_id end def set_default_feature_flags - self.enable_feature!(:new_user_tutorial_on_off) unless Rails.env.test? + enable_feature!(:new_user_tutorial_on_off) unless Rails.env.test? end def sortable_name @@ -902,13 +902,13 @@ def sortable_name end def primary_pseudonym - self.pseudonyms.active.first + pseudonyms.active.first end def primary_pseudonym=(p) p = Pseudonym.find(p) p.move_to_top - self.reload + reload end def email_channel @@ -929,19 +929,19 @@ def email end def email_cache_key - ['user_email', self.global_id].cache_key + ['user_email', global_id].cache_key end def cached_active_emails - self.shard.activate do + shard.activate do Rails.cache.fetch(active_emails_cache_key) do - self.communication_channels.active.email.pluck(:path) + communication_channels.active.email.pluck(:path) end end end def active_emails_cache_key - ['active_user_emails', self.global_id].cache_key + ['active_user_emails', global_id].cache_key end def clear_email_cache! @@ -954,10 +954,10 @@ def email_cached? end def gmail_channel - addr = self.user_services - .where(service_domain: "google.com") - .limit(1).pluck(:service_user_id).first - self.communication_channels.email.by_path(addr).first + addr = user_services + .where(service_domain: "google.com") + .limit(1).pluck(:service_user_id).first + communication_channels.email.by_path(addr).first end def gmail @@ -976,16 +976,16 @@ def google_drive_address end def google_service_address(service_name) - self.user_services.where(service: service_name) - .limit(1).pluck(service_name == 'google_drive' ? :service_user_name : :service_user_id).first + user_services.where(service: service_name) + .limit(1).pluck(service_name == 'google_drive' ? :service_user_name : :service_user_id).first end def email=(e) - if e.is_a?(CommunicationChannel) && e.user_id == self.id + if e.is_a?(CommunicationChannel) && e.user_id == id cc = e else - cc = self.communication_channels.email.by_path(e).first || - self.communication_channels.email.create!(path: e) + cc = communication_channels.email.by_path(e).first || + communication_channels.email.create!(path: e) # If the email already exists but with different casing this allows us to change it cc.path = e cc.user = self @@ -993,8 +993,8 @@ def email=(e) cc.move_to_top cc.workflow_state = 'unconfirmed' if cc.retired? cc.save! - self.reload - self.clear_email_cache! + reload + clear_email_cache! cc.path end @@ -1037,23 +1037,23 @@ def unavailable? end def clear_caches - self.clear_cache_key(*Canvas::CacheRegister::ALLOWED_TYPES['User']) - self.touch + clear_cache_key(*Canvas::CacheRegister::ALLOWED_TYPES['User']) + touch end alias_method :destroy_permanently!, :destroy def destroy - self.remove_from_root_account(:all) + remove_from_root_account(:all) self.workflow_state = 'deleted' self.deleted_at = Time.now.utc - if self.save + if save eportfolios.active.in_batches.destroy_all gradebook_filters.in_batches.destroy_all end end # avoid extraneous callbacks when enrolled in multiple sections - def delete_enrollments(enrollment_scope = self.enrollments, updating_user: nil) + def delete_enrollments(enrollment_scope = enrollments, updating_user: nil) courses_to_update = enrollment_scope.active.distinct.pluck(:course_id) Enrollment.suspend_callbacks(:set_update_cached_due_dates) do enrollment_scope.preload(:course, :enrollment_state).each(&:destroy) @@ -1068,37 +1068,37 @@ def remove_from_root_account(root_account, updating_user: nil) ActiveRecord::Base.transaction do if root_account == :all # make sure to hit all shards - enrollment_scope = self.enrollments.shard(self) - user_observer_scope = self.as_student_observation_links.shard(self) - user_observee_scope = self.as_observer_observation_links.shard(self) - pseudonym_scope = self.pseudonyms.active.shard(self) + enrollment_scope = enrollments.shard(self) + user_observer_scope = as_student_observation_links.shard(self) + user_observee_scope = as_observer_observation_links.shard(self) + pseudonym_scope = pseudonyms.active.shard(self) account_users = self.account_users.active.shard(self) has_other_root_accounts = false - group_memberships_scope = self.group_memberships.active.shard(self) + group_memberships_scope = group_memberships.active.shard(self) # eportfolios will only be in the users home shard - eportfolio_scope = self.eportfolios.active + eportfolio_scope = eportfolios.active else # make sure to do things on the root account's shard. but note, # root_account.enrollments won't include the student view user's # enrollments, so we need to fetch them off the user instead; the # student view user won't be cross shard, so that will still be the # right shard - enrollment_scope = fake_student? ? self.enrollments : root_account.enrollments.where(user_id: self) - user_observer_scope = self.as_student_observation_links.shard(self) - user_observee_scope = self.as_observer_observation_links.shard(self) + enrollment_scope = fake_student? ? enrollments : root_account.enrollments.where(user_id: self) + user_observer_scope = as_student_observation_links.shard(self) + user_observee_scope = as_observer_observation_links.shard(self) pseudonym_scope = root_account.pseudonyms.active.where(user_id: self) account_users = root_account.account_users.where(user_id: self).to_a + self.account_users.shard(root_account).where(:account_id => root_account.all_accounts).to_a - has_other_root_accounts = self.associated_accounts.shard(self).where.not(accounts: { id: root_account }).exists? - group_memberships_scope = self.group_memberships.active.shard(root_account.shard).joins(:group).where(:groups => { :root_account_id => root_account }) + has_other_root_accounts = associated_accounts.shard(self).where.not(accounts: { id: root_account }).exists? + group_memberships_scope = group_memberships.active.shard(root_account.shard).joins(:group).where(:groups => { :root_account_id => root_account }) - eportfolio_scope = self.eportfolios.active if self.shard == root_account.shard + eportfolio_scope = eportfolios.active if shard == root_account.shard end - self.delete_enrollments(enrollment_scope, updating_user: updating_user) + delete_enrollments(enrollment_scope, updating_user: updating_user) group_memberships_scope.destroy_all user_observer_scope.destroy_all user_observee_scope.destroy_all @@ -1109,11 +1109,11 @@ def remove_from_root_account(root_account, updating_user: nil) # only delete the user's communication channels when the last account is # removed (they don't belong to any particular account). they will always # be on the user's shard - self.communication_channels.unretired.each(&:destroy) unless has_other_root_accounts + communication_channels.unretired.each(&:destroy) unless has_other_root_accounts - self.update_account_associations + update_account_associations end - self.reload + reload end def associate_with_shard(shard, strength = :strong); end @@ -1134,7 +1134,7 @@ def self.clone_communication_channel(cc, new_user, max_position) # Overwrites the old user name, if there was one. Fills in the new one otherwise. def assert_name(name = nil) - if name && (self.pre_registered? || self.creation_pending?) && name != email + if name && (pre_registered? || creation_pending?) && name != email self.name = name save! end @@ -1144,10 +1144,10 @@ def assert_name(name = nil) def to_atom Atom::Entry.new do |entry| entry.title = self.name - entry.updated = self.updated_at - entry.published = self.created_at + entry.updated = updated_at + entry.published = created_at entry.links << Atom::Link.new(:rel => 'alternate', - :href => "/users/#{self.id}") + :href => "/users/#{id}") end end @@ -1164,16 +1164,16 @@ def latest_pseudonym end def used_feature(feature) - self.update_attribute(:features_used, ((self.features_used || "").split(",").map(&:to_s) + [feature.to_s]).uniq.join(',')) + update_attribute(:features_used, ((features_used || "").split(",").map(&:to_s) + [feature.to_s]).uniq.join(',')) end def used_feature?(feature) - self.features_used&.split(/,/)&.include?(feature.to_s) + features_used&.split(/,/)&.include?(feature.to_s) end def available_courses # this list should be longer if the person has admin privileges... - self.courses + courses end def check_courses_right?(user, sought_right, enrollments_to_check = nil) @@ -1195,13 +1195,13 @@ def check_accounts_right?(user, sought_right) # check if the user we are given is an admin in one of this user's accounts return false unless user && sought_right return true if Account.site_admin.grants_right?(user, sought_right) - return self.account.grants_right?(user, sought_right) if self.fake_student? # doesn't have account association + return account.grants_right?(user, sought_right) if fake_student? # doesn't have account association common_shards = associated_shards & user.associated_shards search_method = ->(shard) do # new users with creation pending enrollments don't have account associations - if associated_accounts.shard(shard).empty? && common_shards.length == 1 && !self.unavailable? - self.account.grants_right?(user, sought_right) + if associated_accounts.shard(shard).empty? && common_shards.length == 1 && !unavailable? + account.grants_right?(user, sought_right) else associated_accounts.shard(shard).any? { |a| a.grants_right?(user, sought_right) } end @@ -1239,68 +1239,68 @@ def check_accounts_right?(user, sought_right) given { |user| user == self && user.user_can_edit_name? } can :rename - given { |user| self.courses.any? { |c| c.user_is_instructor?(user) } } + given { |user| courses.any? { |c| c.user_is_instructor?(user) } } can :read_profile # by default this means that the user we are given is an administrator # of an account of one of the courses that this user is enrolled in, or # an admin (teacher/ta/designer) in the course - given { |user| self.check_courses_right?(user, :read_reports) } + given { |user| check_courses_right?(user, :read_reports) } can :read_profile and can :remove_avatar and can :read_reports - given { |user| self.check_courses_right?(user, :manage_user_notes) } + given { |user| check_courses_right?(user, :manage_user_notes) } can :create_user_notes and can :read_user_notes [:read_email_addresses, :read_sis, :manage_sis].each do |permission| - given { |user| self.check_courses_right?(user, permission) } + given { |user| check_courses_right?(user, permission) } can permission end - given { |user| self.check_courses_right?(user, :generate_observer_pairing_code, enrollments.not_deleted) } + given { |user| check_courses_right?(user, :generate_observer_pairing_code, enrollments.not_deleted) } can :generate_observer_pairing_code - given { |user| self.check_accounts_right?(user, :manage_user_notes) } + given { |user| check_accounts_right?(user, :manage_user_notes) } can :create_user_notes and can :read_user_notes and can :delete_user_notes - given { |user| self.check_accounts_right?(user, :view_statistics) } + given { |user| check_accounts_right?(user, :view_statistics) } can :view_statistics - given { |user| self.check_accounts_right?(user, :manage_students) } + given { |user| check_accounts_right?(user, :manage_students) } can :read_profile and can :view_statistics and can :read_reports and can :read_grades - given { |user| self.check_accounts_right?(user, :manage_user_logins) } + given { |user| check_accounts_right?(user, :manage_user_logins) } can :read and can :read_reports and can :read_profile and can :api_show_user and can :terminate_sessions - given { |user| self.check_accounts_right?(user, :read_roster) } + given { |user| check_accounts_right?(user, :read_roster) } can :read_full_profile and can :api_show_user - given { |user| self.check_accounts_right?(user, :view_all_grades) } + given { |user| check_accounts_right?(user, :view_all_grades) } can :read_grades - given { |user| self.check_accounts_right?(user, :view_user_logins) } + given { |user| check_accounts_right?(user, :view_user_logins) } can :view_user_logins - given { |user| self.check_accounts_right?(user, :read_email_addresses) } + given { |user| check_accounts_right?(user, :read_email_addresses) } can :read_email_addresses given do |user| - self.check_accounts_right?(user, :manage_user_logins) && self.adminable_accounts.select(&:root_account?).all? { |a| has_subset_of_account_permissions?(user, a) } + check_accounts_right?(user, :manage_user_logins) && adminable_accounts.select(&:root_account?).all? { |a| has_subset_of_account_permissions?(user, a) } end can :manage_user_details and can :rename and can :update_avatar and can :remove_avatar and can :manage_feature_flags and can :view_feature_flags - given { |user| self.pseudonyms.shard(self).any? { |p| p.grants_right?(user, :update) } } + given { |user| pseudonyms.shard(self).any? { |p| p.grants_right?(user, :update) } } can :merge given do |user| # a user can reset their own MFA, but only if the setting isn't required - (self == user && self.mfa_settings != :required) || + (self == user && mfa_settings != :required) || # a site_admin with permission to reset_any_mfa Account.site_admin.grants_right?(user, :reset_any_mfa) || # an admin can reset another user's MFA only if they can manage *all* # of the user's pseudonyms - (self != user && self.pseudonyms.shard(self).all? do |p| + (self != user && pseudonyms.shard(self).all? do |p| p.grants_right?(user, :update) || # the account does not have mfa enabled p.account.mfa_settings == :disabled || @@ -1310,17 +1310,17 @@ def check_accounts_right?(user, sought_right) end can :reset_mfa - given { |user| user && user.as_observer_observation_links.where(user_id: self.id).exists? } + given { |user| user && user.as_observer_observation_links.where(user_id: id).exists? } can :read and can :read_as_parent - given { |user| self.check_accounts_right?(user, :moderate_user_content) } + given { |user| check_accounts_right?(user, :moderate_user_content) } can :moderate_user_content end def can_masquerade?(masquerader, account) return true if self == masquerader # student view should only ever have enrollments in a single course - return true if self.fake_student? && self.courses.any? { |c| c.grants_right?(masquerader, :use_student_view) } + return true if fake_student? && courses.any? { |c| c.grants_right?(masquerader, :use_student_view) } return false unless account.grants_right?(masquerader, nil, :become_user) && SisPseudonym.for(self, account, type: :implicit, require_sis: false) @@ -1361,19 +1361,19 @@ def self.infer_id(obj) end def management_contexts - contexts = [self] + self.courses + self.groups.active + self.all_courses_for_active_enrollments + contexts = [self] + courses + groups.active + all_courses_for_active_enrollments contexts.uniq end def update_avatar_image(force_reload = false) - if !self.avatar_image_url || force_reload - if self.avatar_image_source == 'twitter' - twitter = self.user_services.for_service('twitter').first rescue nil + if !avatar_image_url || force_reload + if avatar_image_source == 'twitter' + twitter = user_services.for_service('twitter').first rescue nil if twitter url = URI.parse("http://twitter.com/users/show.json?user_id=#{twitter.service_user_id}") data = JSON.parse(Net::HTTP.get(url)) rescue nil if data - self.avatar_image_url = data['profile_image_url_https'] || self.avatar_image_url + self.avatar_image_url = data['profile_image_url_https'] || avatar_image_url self.avatar_image_updated_at = Time.now end end @@ -1399,7 +1399,7 @@ def max_messages_per_day def gravatar_url(size = 50, fallback = nil, request = nil) fallback = self.class.avatar_fallback_url(fallback, request) - "https://secure.gravatar.com/avatar/#{Digest::MD5.hexdigest(self.email) rescue '000'}?s=#{size}&d=#{CGI.escape(fallback)}" + "https://secure.gravatar.com/avatar/#{Digest::MD5.hexdigest(email) rescue '000'}?s=#{size}&d=#{CGI.escape(fallback)}" end # Public: Set a user's avatar image. This is a convenience method that sets @@ -1445,12 +1445,12 @@ def avatar_image=(val) end def report_avatar_image! - self.avatar_state = if self.avatar_state == :approved || self.avatar_state == :locked + self.avatar_state = if avatar_state == :approved || avatar_state == :locked 're_reported' else 'reported' end - self.save! + save! end def avatar_state @@ -1510,17 +1510,17 @@ def avatar_url(size = nil, avatar_setting = nil, fallback = nil, request = nil, avatar_setting ||= 'enabled' fallback = use_fallback ? self.class.avatar_fallback_url(fallback, request) : nil if avatar_setting == 'enabled' || (avatar_setting == 'enabled_pending' && avatar_approved?) || (avatar_setting == 'sis_only') - @avatar_url ||= self.avatar_image_url + @avatar_url ||= avatar_image_url end - @avatar_url ||= fallback if self.avatar_image_source == 'no_pic' - if (avatar_setting == 'enabled') && (self.avatar_image_source == 'gravatar') + @avatar_url ||= fallback if avatar_image_source == 'no_pic' + if (avatar_setting == 'enabled') && (avatar_image_source == 'gravatar') @avatar_url ||= gravatar_url(size, fallback, request) end @avatar_url ||= fallback end def avatar_path - "/images/users/#{User.avatar_key(self.id)}" + "/images/users/#{User.avatar_key(id)}" end def self.default_avatar_fallback @@ -1559,9 +1559,9 @@ def self.avatar_fallback_url(fallback = nil, request = nil) def clear_avatar_image_url_with_uuid(uuid) raise ArgumentError, "'uuid' is required and cannot be blank" if uuid.blank? - if self.avatar_image_url.to_s.match?(/#{uuid}/) + if avatar_image_url.to_s.match?(/#{uuid}/) self.avatar_image_url = nil - self.save + save end end @@ -1575,8 +1575,8 @@ def clear_avatar_image_url_with_uuid(uuid) } def sorted_rubrics - context_codes = ([self] + self.management_contexts).uniq.map(&:asset_string) - rubrics = self.context_rubrics.active + context_codes = ([self] + management_contexts).uniq.map(&:asset_string) + rubrics = context_rubrics.active rubrics += Rubric.active.where(context_code: context_codes).to_a rubrics.uniq.sort_by { |r| [(r.association_count || 0) > 3 ? CanvasSort::First : CanvasSort::Last, Canvas::ICU.collation_key(r.title || CanvasSort::Last)] } end @@ -1596,14 +1596,14 @@ def new_user_tutorial_statuses def custom_colors colors_hash = get_preference(:custom_colors) || {} - if Shard.current != self.shard + if Shard.current != shard # translate asset strings to be relative to current shard colors_hash = colors_hash.filter_map do |asset_string, value| opts = asset_string.split("_") id_relative_to_user_shard = opts.pop.to_i - next if id_relative_to_user_shard > Shard::IDS_PER_SHARD && Shard.shard_for(id_relative_to_user_shard) == self.shard # this is old data and should be ignored + next if id_relative_to_user_shard > Shard::IDS_PER_SHARD && Shard.shard_for(id_relative_to_user_shard) == shard # this is old data and should be ignored - new_id = Shard.relative_id_for(id_relative_to_user_shard, self.shard, Shard.current) + new_id = Shard.relative_id_for(id_relative_to_user_shard, shard, Shard.current) ["#{opts.join('_')}_#{new_id}", value] end.to_h end @@ -1632,7 +1632,7 @@ def dashboard_view=(new_dashboard_view) def all_course_nicknames(courses = nil) if preferences[:course_nicknames] == UserPreferenceValue::EXTERNAL - self.shard.activate do + shard.activate do scope = user_preference_values.where(:key => :course_nicknames) scope = scope.where(sub_key: courses) if courses scope.pluck(:sub_key, :value).to_h @@ -1672,7 +1672,7 @@ def send_observed_names_in_notifications? def close_announcement(announcement) closed = get_preference(:closed_notifications).dup || [] # serialize ids relative to the user - self.shard.activate do + shard.activate do closed << announcement.id end set_preference(:closed_notifications, closed.uniq) @@ -1779,7 +1779,7 @@ def comment_library_suggestions_enabled? def uuid unless read_attribute(:uuid) - self.update_attribute(:uuid, CanvasSlug.generate_securish_uuid) + update_attribute(:uuid, CanvasSlug.generate_securish_uuid) end read_attribute(:uuid) end @@ -1797,7 +1797,7 @@ def self.serialization_excludes end def secondary_identifier - self.email || self.id + email || id end def self_enroll_if_necessary @@ -1814,7 +1814,7 @@ def is_a_context? end def account - self.pseudonym.account rescue Account.default + pseudonym.account rescue Account.default end # this finds the reverse account chain starting at in_root_account and ending @@ -1826,7 +1826,7 @@ def account def common_account_chain(in_root_account) GuardRail.activate(:secondary) do rid = in_root_account.id - accts = self.associated_accounts.where("accounts.id = ? OR accounts.root_account_id = ?", rid, rid) + accts = associated_accounts.where("accounts.id = ? OR accounts.root_account_id = ?", rid, rid) return [] if accts.blank? children = accts.each_with_object({}) do |acct, hash| @@ -1862,7 +1862,7 @@ def courses_with_primary_enrollment(association = :current_and_invited_courses, cache_key = [association, enrollment_uuid, options].cache_key @courses_with_primary_enrollment ||= {} @courses_with_primary_enrollment.fetch(cache_key) do - res = self.shard.activate do + res = shard.activate do result = Rails.cache.fetch([self, 'courses_with_primary_enrollment2', association, options, ApplicationController.region].cache_key, :expires_in => 15.minutes) do # Set the actual association based on if its asking for favorite courses or not. actual_association = association == :favorite_courses ? :current_and_invited_courses : association @@ -1870,7 +1870,7 @@ def courses_with_primary_enrollment(association = :current_and_invited_courses, shards = in_region_associated_shards # Limit favorite courses based on current shard. if association == :favorite_courses - ids = self.favorite_context_ids("Course") + ids = favorite_context_ids("Course") if ids.empty? scope = scope.none else @@ -1933,12 +1933,12 @@ def courses_with_primary_enrollment(association = :current_and_invited_courses, end def temporary_invitations - cached_active_emails.map { |email| Enrollment.cached_temporary_invitations(email).dup.reject { |e| e.user_id == self.id } }.flatten + cached_active_emails.map { |email| Enrollment.cached_temporary_invitations(email).dup.reject { |e| e.user_id == id } }.flatten end def active_k5_enrollments? account_ids = - self.enrollments.shard(in_region_associated_shards).current.active_by_date.distinct.pluck(:account_id) + enrollments.shard(in_region_associated_shards).current.active_by_date.distinct.pluck(:account_id) Account.where(id: account_ids).any?(&:enable_as_k5_account?) end @@ -1952,7 +1952,7 @@ def cached_currentish_enrollments(opts = {}) # leaving this for existing instances where schools are used to the inconsistent behavior # participating_enrollments seems to be a more accurate representation of "current courses" RequestCache.cache('cached_current_enrollments', self, opts) do - enrollments = self.shard.activate do + enrollments = shard.activate do res = Rails.cache.fetch_with_batched_keys( ['current_enrollments4', opts[:include_future], ApplicationController.region].cache_key, batch_object: self, batched_keys: :enrollments @@ -1996,7 +1996,7 @@ def has_enrollment? # don't need an expires_at here because user will be touched upon enrollment creation @_has_enrollment = Rails.cache.fetch([self, 'has_enrollment', ApplicationController.region].cache_key) do - self.enrollments.shard(in_region_associated_shards).active.exists? + enrollments.shard(in_region_associated_shards).active.exists? end end @@ -2005,7 +2005,7 @@ def has_active_enrollment? # don't need an expires_at here because user will be touched upon enrollment activation @_has_active_enrollment = Rails.cache.fetch([self, 'has_active_enrollment', ApplicationController.region].cache_key) do - self.enrollments.shard(in_region_associated_shards).current.active_by_date.exists? + enrollments.shard(in_region_associated_shards).current.active_by_date.exists? end end @@ -2013,22 +2013,22 @@ def has_future_enrollment? return @_has_future_enrollment if defined?(@_has_future_enrollment) @_has_future_enrollment = Rails.cache.fetch([self, 'has_future_enrollment', ApplicationController.region].cache_key, :expires_in => 1.hour) do - self.enrollments.shard(in_region_associated_shards).active_or_pending_by_date.exists? + enrollments.shard(in_region_associated_shards).active_or_pending_by_date.exists? end end def cached_current_group_memberships - @cached_current_group_memberships ||= self.shard.activate do + @cached_current_group_memberships ||= shard.activate do Rails.cache.fetch_with_batched_keys(['current_group_memberships', ApplicationController.region].cache_key, batch_object: self, batched_keys: :groups) do - self.current_group_memberships.shard(self.in_region_associated_shards).to_a + current_group_memberships.shard(in_region_associated_shards).to_a end end end def cached_current_group_memberships_by_date - @cached_current_group_memberships_by_date ||= self.shard.activate do + @cached_current_group_memberships_by_date ||= shard.activate do Rails.cache.fetch_with_batched_keys(['current_group_memberships_by_date', ApplicationController.region].cache_key, batch_object: self, batched_keys: [:enrollments, :groups]) do - Shard.with_each_shard(self.in_region_associated_shards) do + Shard.with_each_shard(in_region_associated_shards) do GroupMembership.where(:user_id => self).joins(:group) .joins("LEFT OUTER JOIN #{Enrollment.quoted_table_name} ON enrollments.user_id=group_memberships.user_id AND enrollments.course_id=groups.context_id AND groups.context_type='Course'") .joins("LEFT OUTER JOIN #{EnrollmentState.quoted_table_name} ON enrollment_states.enrollment_id=enrollments.id") @@ -2042,8 +2042,8 @@ def has_student_enrollment? return @_has_student_enrollment if defined?(@_has_student_enrollment) @_has_student_enrollment = Rails.cache.fetch_with_batched_keys(['has_student_enrollment', ApplicationController.region].cache_key, batch_object: self, batched_keys: :enrollments) do - self.enrollments.shard(in_region_associated_shards).where(:type => %w[StudentEnrollment StudentViewEnrollment]) - .where.not(:workflow_state => %w[rejected inactive deleted]).exists? + enrollments.shard(in_region_associated_shards).where(:type => %w[StudentEnrollment StudentViewEnrollment]) + .where.not(:workflow_state => %w[rejected inactive deleted]).exists? end end @@ -2052,8 +2052,8 @@ def non_student_enrollment? return @_non_student_enrollment if defined?(@_non_student_enrollment) @_non_student_enrollment = Rails.cache.fetch_with_batched_keys(['has_non_student_enrollment', ApplicationController.region].cache_key, batch_object: self, batched_keys: :enrollments) do - self.enrollments.shard(in_region_associated_shards).where.not(type: %w[StudentEnrollment StudentViewEnrollment ObserverEnrollment]) - .where.not(workflow_state: %w[rejected inactive deleted]).exists? + enrollments.shard(in_region_associated_shards).where.not(type: %w[StudentEnrollment StudentViewEnrollment ObserverEnrollment]) + .where.not(workflow_state: %w[rejected inactive deleted]).exists? end end @@ -2061,7 +2061,7 @@ def account_membership? return @_account_membership if defined?(@_account_membership) @_account_membership = Rails.cache.fetch_with_batched_keys(['has_account_user', ApplicationController.region].cache_key, batch_object: self, batched_keys: :account_users) do - self.account_users.shard(in_region_associated_shards).active.exists? + account_users.shard(in_region_associated_shards).active.exists? end end @@ -2114,18 +2114,18 @@ def all_course_ids def cached_course_ids(type) @cached_course_ids ||= {} @cached_course_ids[type] ||= - self.shard.activate do + shard.activate do Rails.cache.fetch_with_batched_keys(["cached_course_ids", type, ApplicationController.region].cache_key, batch_object: self, batched_keys: :enrollments) do - yield(self.enrollments.shard(in_region_associated_shards)).distinct.pluck(:course_id) + yield(enrollments.shard(in_region_associated_shards)).distinct.pluck(:course_id) end end end private :cached_course_ids def participating_enrollments - @participating_enrollments ||= self.shard.activate do + @participating_enrollments ||= shard.activate do Rails.cache.fetch_with_batched_keys([self, 'participating_enrollments2', ApplicationController.region].cache_key, batch_object: self, batched_keys: :enrollments) do - self.enrollments.shard(in_region_associated_shards).current.active_by_date.to_a.each(&:clear_association_cache) + enrollments.shard(in_region_associated_shards).current.active_by_date.to_a.each(&:clear_association_cache) end end end @@ -2173,7 +2173,7 @@ def recent_feedback( course_ids ||= if contexts contexts.select { |c| c.is_a?(Course) }.map(&:id) else - self.participating_student_course_ids + participating_student_course_ids end submissions_for_course_ids(course_ids, **opts) end @@ -2192,7 +2192,7 @@ def visible_stream_item_instances(opts = {}) elsif opts[:context] instances = instances.where(context: opts[:context]) elsif opts[:only_active_courses] - instances = instances.where(:context_type => "Course", :context_id => self.participating_course_ids) + instances = instances.where(:context_type => "Course", :context_id => participating_course_ids) end instances @@ -2227,7 +2227,7 @@ def cached_recent_stream_items(opts = {}) # NOTE: excludes submission stream items def recent_stream_items(opts = {}) - self.shard.activate do + shard.activate do GuardRail.activate(:secondary) do visible_instances = visible_stream_item_instances(opts) .preload(stream_item: :context) @@ -2236,7 +2236,7 @@ def recent_stream_items(opts = {}) si = sii.stream_item next if si.blank? next if si.asset_type == 'Submission' - next if si.context_type == "Course" && (si.context.concluded? || self.participating_enrollments.none? { |e| e.course_id == si.context_id }) + next if si.context_type == "Course" && (si.context.concluded? || participating_enrollments.none? { |e| e.course_id == si.context_id }) si.unread = sii.unread? si @@ -2246,7 +2246,7 @@ def recent_stream_items(opts = {}) end def upcoming_events(opts = {}) - context_codes = opts[:context_codes] || (opts[:contexts] ? setup_context_lookups(opts[:contexts]) : self.cached_context_codes) + context_codes = opts[:context_codes] || (opts[:contexts] ? setup_context_lookups(opts[:contexts]) : cached_context_codes) return [] if !context_codes || context_codes.empty? now = Time.zone.now @@ -2260,7 +2260,7 @@ def upcoming_events(opts = {}) filter_after_db = !opts[:use_db_filter] && (context_codes.grep(/\Acourse_\d+\z/).count > Setting.get('filter_events_by_section_code_threshold', '25').to_i) - section_codes = self.section_context_codes(context_codes, filter_after_db) + section_codes = section_context_codes(context_codes, filter_after_db) limit = filter_after_db ? opts[:limit] * 2 : opts[:limit] # pull extra events just in case events = CalendarEvent.active.for_user_and_context_codes(self, context_codes, section_codes) .between(now, opts[:end_at]).limit(limit).order(:start_at).to_a.reject(&:hidden?) @@ -2271,14 +2271,14 @@ def upcoming_events(opts = {}) section_ids = events.map(&:context_code).grep(/\Acourse_section_\d+\z/).map { |s| s.delete_prefix('course_section_').to_i } section_course_codes = Course.joins(:course_sections).where(:course_sections => { :id => section_ids }) .pluck(:id).map { |id| "course_#{id}" } - visible_section_codes = self.section_context_codes(section_course_codes) + visible_section_codes = section_context_codes(section_course_codes) events.reject! { |e| e.context_code.start_with?("course_section_") && !visible_section_codes.include?(e.context_code) } events = events.first(opts[:limit]) # strip down to the original limit end # if we've filtered too many (which should be unlikely), just fallback on the old behavior if original_count >= opts[:limit] && events.count < opts[:limit] - return self.upcoming_events(opts.merge(:use_db_filter => true)) + return upcoming_events(opts.merge(:use_db_filter => true)) end end @@ -2317,7 +2317,7 @@ def select_available_assignments(assignments, include_concluded: false) all_course_ids else Shard.partition_by_shard(assignments.map(&:context_id).uniq) do |course_ids| - self.enrollments.shard(Shard.current).where(course_id: course_ids).active_by_date.pluck(:course_id) + enrollments.shard(Shard.current).where(course_id: course_ids).active_by_date.pluck(:course_id) end end @@ -2339,7 +2339,7 @@ def select_upcoming_assignments(assignments, opts) def undated_events(opts = {}) opts = opts.dup - context_codes = opts[:context_codes] || (opts[:contexts] ? setup_context_lookups(opts[:contexts]) : self.cached_context_codes) + context_codes = opts[:context_codes] || (opts[:contexts] ? setup_context_lookups(opts[:contexts]) : cached_context_codes) return [] if !context_codes || context_codes.empty? undated_events = [] @@ -2357,10 +2357,10 @@ def cached_context_codes # (hopefully) don't need to include cross-shard because calendar events/assignments/etc are only seached for on current shard anyway @cached_context_codes ||= Rails.cache.fetch([self, 'cached_context_codes', Shard.current].cache_key, :expires_in => 15.minutes) do - group_ids = self.groups.active.pluck(:id) + group_ids = groups.active.pluck(:id) cached_current_course_ids = Rails.cache.fetch([self, 'cached_current_course_ids', Shard.current].cache_key) do # don't need an expires at because user will be touched if enrollment state changes from 'active' - self.enrollments.shard(Shard.current).current.active_by_date.distinct.pluck(:course_id) + enrollments.shard(Shard.current).current.active_by_date.distinct.pluck(:course_id) end cached_current_course_ids.map { |id| "course_#{id}" } + group_ids.map { |id| "group_#{id}" } @@ -2526,23 +2526,23 @@ def section_context_codes(context_codes, skip_visibility_filter = false) end def manageable_courses(include_concluded = false) - Course.manageable_by_user(self.id, include_concluded).not_deleted + Course.manageable_by_user(id, include_concluded).not_deleted end def manageable_courses_by_query(query = '', include_concluded = false) - self.manageable_courses(include_concluded).not_deleted.name_like(query).limit(50) + manageable_courses(include_concluded).not_deleted.name_like(query).limit(50) end def last_completed_module - self.context_module_progressions.select(&:completed?).max_by { |p| p.completed_at || p.created_at }.context_module rescue nil + context_module_progressions.select(&:completed?).max_by { |p| p.completed_at || p.created_at }.context_module rescue nil end def last_completed_course - self.enrollments.select(&:completed?).max_by { |e| e.completed_at || e.created_at }.course rescue nil + enrollments.select(&:completed?).max_by { |e| e.completed_at || e.created_at }.course rescue nil end def last_mastered_assignment - self.learning_outcome_results.active.sort_by { |r| r.assessed_at || r.created_at }.select(&:mastery?).map(&:assignment).last + learning_outcome_results.active.sort_by { |r| r.assessed_at || r.created_at }.select(&:mastery?).map(&:assignment).last end def profile_pics_folder @@ -2554,9 +2554,9 @@ def conversation_attachments_folder end def initialize_default_folder(name) - folder = self.active_folders.where(name: name).first - folder ||= self.folders.create!(:name => name, - :parent_folder => Folder.root_folders(self).find { |f| f.name == Folder::MY_FILES_FOLDER_NAME }) + folder = active_folders.where(name: name).first + folder ||= folders.create!(:name => name, + :parent_folder => Folder.root_folders(self).find { |f| f.name == Folder::MY_FILES_FOLDER_NAME }) folder end @@ -2651,7 +2651,7 @@ def conversation_participant(conversation_id) # Returns nothing. def reset_unread_conversations_counter(unread_count = nil) unread_count ||= conversations.unread.count - if self.unread_conversations_count != unread_count + if unread_conversations_count != unread_count self.class.where(:id => id).update_all(:unread_conversations_count => unread_count) end end @@ -2670,30 +2670,30 @@ def favorite_context_ids(context_type) context_ids = @favorite_context_ids[context_type] unless context_ids # Only get the users favorites from their shard. - self.shard.activate do + shard.activate do # Get favorites and map them to their global ids. - context_ids = self.favorites.where(context_type: context_type).pluck(:context_id).map { |id| Shard.global_id_for(id) } + context_ids = favorites.where(context_type: context_type).pluck(:context_id).map { |id| Shard.global_id_for(id) } @favorite_context_ids[context_type] = context_ids end end # Return ids relative for the current shard context_ids.map { |id| - Shard.relative_id_for(id, self.shard, Shard.current) + Shard.relative_id_for(id, shard, Shard.current) } end def menu_courses(enrollment_uuid = nil, opts = {}) return @menu_courses if @menu_courses - can_favorite = proc { |c| !(c.elementary_subject_course? || c.elementary_homeroom_course?) || c.user_is_admin?(self) || self.roles(c.root_account).include?('teacher') } + can_favorite = proc { |c| !(c.elementary_subject_course? || c.elementary_homeroom_course?) || c.user_is_admin?(self) || roles(c.root_account).include?('teacher') } # this terribleness is so we try to make sure that the newest courses show up in the menu - courses = self.courses_with_primary_enrollment(:current_and_invited_courses, enrollment_uuid, opts) - .sort_by { |c| [c.primary_enrollment_rank, Time.now - (c.primary_enrollment_date || Time.now)] } - .first(Setting.get('menu_course_limit', '20').to_i) - .sort_by { |c| [c.primary_enrollment_rank, Canvas::ICU.collation_key(c.name)] } - favorites = self.courses_with_primary_enrollment(:favorite_courses, enrollment_uuid, opts) - .select { |c| can_favorite.call(c) } + courses = courses_with_primary_enrollment(:current_and_invited_courses, enrollment_uuid, opts) + .sort_by { |c| [c.primary_enrollment_rank, Time.now - (c.primary_enrollment_date || Time.now)] } + .first(Setting.get('menu_course_limit', '20').to_i) + .sort_by { |c| [c.primary_enrollment_rank, Canvas::ICU.collation_key(c.name)] } + favorites = courses_with_primary_enrollment(:favorite_courses, enrollment_uuid, opts) + .select { |c| can_favorite.call(c) } # if favoritable courses (classic courses or k5 courses with admin enrollment) exist, show those and all non-favoritable courses @menu_courses = if !favorites.empty? favorites + courses.reject { |c| can_favorite.call(c) } @@ -2742,13 +2742,13 @@ def can_create_enrollment_for?(course, session, type) def can_be_enrolled_in_course?(course) !!SisPseudonym.for(self, course, type: :implicit, require_sis: false) || - (self.creation_pending? && self.enrollments.where(course_id: course).exists?) + (creation_pending? && enrollments.where(course_id: course).exists?) end def group_member_json(context) - h = { :user_id => self.id, :name => self.last_name_first, :display_name => self.short_name } + h = { :user_id => id, :name => last_name_first, :display_name => self.short_name } if context.is_a?(Course) - self.sections_for_course(context).each do |section| + sections_for_course(context).each do |section| h[:sections] ||= [] h[:sections] << { :section_id => section.id, :section_code => section.section_code } end @@ -2764,7 +2764,7 @@ def find_or_initialize_pseudonym_for_account(account, preferred_template_account pseudonym = SisPseudonym.for(self, account, type: :trusted, require_sis: false) unless pseudonym # list of copyable pseudonyms - active_pseudonyms = self.all_active_pseudonyms(:reload).select { |p| !p.password_auto_generated? && !p.account.delegated_authentication? } + active_pseudonyms = all_active_pseudonyms(:reload).select { |p| !p.password_auto_generated? && !p.account.delegated_authentication? } templates = [] # re-arrange in the order we prefer templates.concat(active_pseudonyms.select { |p| p.account_id == preferred_template_account.id }) if preferred_template_account @@ -2787,7 +2787,7 @@ def find_or_initialize_pseudonym_for_account(account, preferred_template_account end def fake_student? - self.preferences[:fake_student] && !!self.enrollments.where(:type => 'StudentViewEnrollment').first + preferences[:fake_student] && !!enrollments.where(:type => 'StudentViewEnrollment').first end def private? @@ -2809,7 +2809,7 @@ def otp_secret_key_remember_me_cookie(time, current_cookie, remote_ip = nil, opt _, ips, _ = parse_otp_remember_me_cookie(current_cookie) cookie = [time.to_i, *[*ips, remote_ip].compact.sort].join('-') - hmac_string = "#{cookie}.#{self.otp_secret_key}" + hmac_string = "#{cookie}.#{otp_secret_key}" return hmac_string if options[:hmac_string] "#{cookie}-#{Canvas::Security.hmac_sha1(hmac_string)}" @@ -2825,7 +2825,7 @@ def validate_otp_secret_key_remember_me_cookie(value, remote_ip = nil) def otp_secret_key return nil unless otp_secret_key_enc - Canvas::Security.decrypt_password(otp_secret_key_enc, otp_secret_key_salt, 'otp_secret_key', self.shard.settings[:encryption_key]) if otp_secret_key_enc + Canvas::Security.decrypt_password(otp_secret_key_enc, otp_secret_key_salt, 'otp_secret_key', shard.settings[:encryption_key]) if otp_secret_key_enc end def otp_secret_key=(key) @@ -2910,7 +2910,7 @@ def weekly_notification_bucket # morning and 11pm saturday night on the DST transition days, but # midnight sunday morning the rest of the time. account_bucket = (shard.id.to_i + pseudonym.try(:account_id).to_i) % DelayedMessage::WEEKLY_ACCOUNT_BUCKETS - user_bucket = self.id % DelayedMessage::MINUTES_PER_WEEKLY_ACCOUNT_BUCKET + user_bucket = id % DelayedMessage::MINUTES_PER_WEEKLY_ACCOUNT_BUCKET (account_bucket * DelayedMessage::MINUTES_PER_WEEKLY_ACCOUNT_BUCKET) + user_bucket end @@ -2972,7 +2972,7 @@ def in_region_associated_shards def adminable_accounts_scope # i couldn't get EXISTS (?) to work multi-shard, so this is happening instead - account_ids = self.account_users.active.shard(self.in_region_associated_shards).distinct.pluck(:account_id) + account_ids = account_users.active.shard(in_region_associated_shards).distinct.pluck(:account_id) Account.active.where(:id => account_ids) end @@ -2985,7 +2985,7 @@ def adminable_accounts end def all_paginatable_accounts - ShardedBookmarkedCollection.build(Account::Bookmarker, self.adminable_accounts_scope.order(:name, :id)) + ShardedBookmarkedCollection.build(Account::Bookmarker, adminable_accounts_scope.order(:name, :id)) end def all_pseudonyms_loaded? @@ -2993,7 +2993,7 @@ def all_pseudonyms_loaded? end def all_pseudonyms - @all_pseudonyms ||= self.pseudonyms.shard(self).to_a + @all_pseudonyms ||= pseudonyms.shard(self).to_a end def all_active_pseudonyms_loaded? @@ -3003,10 +3003,10 @@ def all_active_pseudonyms_loaded? def current_active_groups? return @_current_active_groups if defined?(@_current_active_groups) - @_current_active_groups = self.shard.activate do + @_current_active_groups = shard.activate do Rails.cache.fetch_with_batched_keys(['current_active_groups', ApplicationController.region].cache_key, batch_object: self, batched_keys: :groups) do - return true if self.current_groups.preload(:context).any?(&:context_available?) - return true if self.current_groups.shard(self.in_region_associated_shards).preload(:context).any?(&:context_available?) + return true if current_groups.preload(:context).any?(&:context_available?) + return true if current_groups.shard(in_region_associated_shards).preload(:context).any?(&:context_available?) false end @@ -3015,7 +3015,7 @@ def current_active_groups? def all_active_pseudonyms(reload = false) @all_active_pseudonyms = nil if reload - @all_active_pseudonyms ||= self.pseudonyms.shard(self).active.to_a + @all_active_pseudonyms ||= pseudonyms.shard(self).active.to_a end def preferred_gradebook_version @@ -3031,29 +3031,29 @@ def stamp_logout_time! end def content_exports_visible_to(user) - self.content_exports.where(user_id: user) + content_exports.where(user_id: user) end def show_bouncing_channel_message! unless show_bouncing_channel_message? - self.preferences[:show_bouncing_channel_message] = true - self.save! + preferences[:show_bouncing_channel_message] = true + save! end end def show_bouncing_channel_message? - !!self.preferences[:show_bouncing_channel_message] + !!preferences[:show_bouncing_channel_message] end def dismiss_bouncing_channel_message! if show_bouncing_channel_message? - self.preferences[:show_bouncing_channel_message] = false - self.save! + preferences[:show_bouncing_channel_message] = false + save! end end def bouncing_channel_message_dismissed? - self.preferences[:show_bouncing_channel_message] == false + preferences[:show_bouncing_channel_message] == false end def update_bouncing_channel_message!(channel = nil) @@ -3079,28 +3079,28 @@ def locale def submissions_folder(for_course = nil) shard.activate do if for_course - parent_folder = self.submissions_folder + parent_folder = submissions_folder Folder.unique_constraint_retry do - self.folders.where(parent_folder_id: parent_folder, submission_context_code: for_course.asset_string) - .first_or_create!(name: for_course.name) + folders.where(parent_folder_id: parent_folder, submission_context_code: for_course.asset_string) + .first_or_create!(name: for_course.name) end else return @submissions_folder if @submissions_folder Folder.unique_constraint_retry do - @submissions_folder = self.folders.where(parent_folder_id: Folder.root_folders(self).first, - submission_context_code: 'root') - .first_or_create!(name: I18n.t('Submissions', locale: self.locale)) + @submissions_folder = folders.where(parent_folder_id: Folder.root_folders(self).first, + submission_context_code: 'root') + .first_or_create!(name: I18n.t('Submissions', locale: locale)) end end end end def submittable_attachments - self.attachments.active.or( + attachments.active.or( Attachment.active.where( context_type: 'Group', - context_id: self.current_group_memberships.active.select(:group_id) + context_id: current_group_memberships.active.select(:group_id) ) ) end diff --git a/app/models/user_learning_object_scopes.rb b/app/models/user_learning_object_scopes.rb index a5e487dda2b99..6bb82a182476b 100644 --- a/app/models/user_learning_object_scopes.rb +++ b/app/models/user_learning_object_scopes.rb @@ -48,7 +48,7 @@ def ignore_item!(asset, purpose, permanent = false) ignore.save! end end - self.touch + touch end def assignments_visible_in_course(course) diff --git a/app/models/user_merge_data.rb b/app/models/user_merge_data.rb index 625072ec90527..77f8b63d4e220 100644 --- a/app/models/user_merge_data.rb +++ b/app/models/user_merge_data.rb @@ -37,10 +37,10 @@ def add_more_data(objects, user: nil, workflow_state: nil, data: []) def build_more_data(objects, user: nil, workflow_state: nil, data: []) # to get relative ids in previous_user_id, we need to be on the records shard - self.shard.activate do + shard.activate do objects.each do |o| user ||= o.user_id - r = self.records.new(context: o, previous_user_id: user) + r = records.new(context: o, previous_user_id: user) r.previous_workflow_state = o.workflow_state if o.class.columns_hash.key?('workflow_state') r.previous_workflow_state = o.file_state if o.instance_of?(Attachment) r.previous_workflow_state = workflow_state if workflow_state @@ -51,7 +51,7 @@ def build_more_data(objects, user: nil, workflow_state: nil, data: []) end def bulk_insert_merge_data(data) - self.shard.activate do + shard.activate do data.each_slice(1000) { |batch| UserMergeDataRecord.bulk_insert_objects(batch) } end end @@ -59,6 +59,6 @@ def bulk_insert_merge_data(data) alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' - self.save! + save! end end diff --git a/app/models/user_note.rb b/app/models/user_note.rb index 18ab705d9484d..60189f134d9b1 100644 --- a/app/models/user_note.rb +++ b/app/models/user_note.rb @@ -40,7 +40,7 @@ class UserNote < ActiveRecord::Base scope :desc_by_date, -> { order('created_at DESC') } set_policy do - given { |user| self.creator == user } + given { |user| creator == user } can :delete and can :read given { |user| self.user.grants_right?(user, :delete_user_notes) } @@ -58,18 +58,18 @@ def destroy end def formatted_note(truncate = nil) - self.extend TextHelper - res = self.note - res = truncate_html(self.note, :max_length => truncate, :words => true) if truncate + extend TextHelper + res = note + res = truncate_html(note, :max_length => truncate, :words => true) if truncate res end def creator_name - self.creator ? self.creator.name : nil + creator ? creator.name : nil end def update_last_user_note - self.user.update_last_user_note - self.user.save + user.update_last_user_note + user.save end end diff --git a/app/models/user_observation_link.rb b/app/models/user_observation_link.rb index 98292f2b01328..82e0c43e65360 100644 --- a/app/models/user_observation_link.rb +++ b/app/models/user_observation_link.rb @@ -52,8 +52,8 @@ def self.create_or_restore(student:, observer:, root_account:, cross_shard_recor shard = cross_shard_record ? observer.shard : student.shard result = shard.activate do - self.unique_constraint_retry do - if (uo = self.where(student: student, observer: observer).for_root_accounts(root_account).take) + unique_constraint_retry do + if (uo = where(student: student, observer: observer).for_root_accounts(root_account).take) if uo.workflow_state == 'deleted' uo.workflow_state = 'active' uo.sis_batch_id = nil @@ -83,21 +83,21 @@ def user alias_method :destroy_permanently!, :destroy def destroy - if !self.skip_destroy_other_record && (other = other_record) + if !skip_destroy_other_record && (other = other_record) other.skip_destroy_other_record = true other.destroy end self.workflow_state = 'deleted' - self.save! + save! remove_linked_enrollments if primary_record? end def not_same_user - self.errors.add(:observer_id, "Cannot observe yourself") if self.user_id == self.observer_id + errors.add(:observer_id, "Cannot observe yourself") if user_id == observer_id end def filter_enrollment_scope(user, scope) - account_ids = [self.root_account.id] + self.root_account.trusted_account_ids + account_ids = [root_account.id] + root_account.trusted_account_ids shards = account_ids.map { |id| Shard.shard_for(id) }.uniq & user.associated_shards scope.shard(shards).where(root_account_id: account_ids) end diff --git a/app/models/user_preference_value.rb b/app/models/user_preference_value.rb index 375417c21d300..3cd4f20d9e704 100644 --- a/app/models/user_preference_value.rb +++ b/app/models/user_preference_value.rb @@ -65,7 +65,7 @@ def self.settings module UserMethods # i could just stuff all this in user.rb directly but it's so full already def needs_preference_migration? - self.preferences.any? do |key, value| + preferences.any? do |key, value| UserPreferenceValue.settings[key] && value.present? && value != EXTERNAL end end @@ -76,7 +76,7 @@ def migrate_preferences_if_needed reorganize_gradebook_preferences # may as well while we're at it UserPreferenceValue.settings.each do |key, settings| - value = self.preferences[key] + value = preferences[key] next unless value.present? next if value == EXTERNAL @@ -87,14 +87,14 @@ def migrate_preferences_if_needed else create_user_preference_value(key, nil, value) end - self.preferences[key] = EXTERNAL + preferences[key] = EXTERNAL end end def get_preference(key, sub_key = nil) - value = self.preferences[key] + value = preferences[key] if value == EXTERNAL - id, value = self.user_preference_values.where(:key => key, :sub_key => sub_key).pluck(:id, :value).first + id, value = user_preference_values.where(:key => key, :sub_key => sub_key).pluck(:id, :value).first mark_preference_row(key, sub_key) if id # if we know there's a row value else @@ -129,26 +129,26 @@ def set_preference(*args) else create_user_preference_value(key, sub_key, value) end - self.preferences[key] = EXTERNAL + preferences[key] = EXTERNAL else - self.preferences[key] = value # can keep a blank value in directly here + preferences[key] = value # can keep a blank value in directly here end - self.changed? ? self.save : true + changed? ? save : true end def clear_all_preferences_for(key) if UserPreferenceValue.settings[key]&.[](:use_sub_keys) - self.user_preference_values.where(:key => key).delete_all + user_preference_values.where(:key => key).delete_all @existing_preference_rows&.clear - self.preferences[key] = {} - self.save! if self.changed? + preferences[key] = {} + save! if changed? else raise "invalid key `#{key}`" end end def preference_row_exists?(key, sub_key) - @existing_preference_rows&.include?([key, sub_key]) || self.user_preference_values.where(:key => key, :sub_key => sub_key).exists? + @existing_preference_rows&.include?([key, sub_key]) || user_preference_values.where(:key => key, :sub_key => sub_key).exists? end def mark_preference_row(key, sub_key) @@ -159,7 +159,7 @@ def mark_preference_row(key, sub_key) def create_user_preference_value(key, sub_key, value) UserPreferenceValue.unique_constraint_retry do |retry_count| if retry_count == 0 - self.user_preference_values.create!(:key => key, :sub_key => sub_key, :value => value) + user_preference_values.create!(:key => key, :sub_key => sub_key, :value => value) else update_user_preference_value(key, sub_key, value) # may already exist end @@ -168,11 +168,11 @@ def create_user_preference_value(key, sub_key, value) end def update_user_preference_value(key, sub_key, value) - self.user_preference_values.where(:key => key, :sub_key => sub_key).update_all(:value => value) + user_preference_values.where(:key => key, :sub_key => sub_key).update_all(:value => value) end def remove_user_preference_value(key, sub_key) - self.user_preference_values.where(:key => key, :sub_key => sub_key).delete_all + user_preference_values.where(:key => key, :sub_key => sub_key).delete_all @existing_preference_rows&.delete([key, sub_key]) end @@ -206,7 +206,7 @@ def reorganize_gradebook_preferences # none of these were set with any shard awareness so just go through all the possible shards and # even if we end up saving data for courses the user doesn't have any rights to it's better than potentially losing it - Shard.with_each_shard(self.associated_shards) do + Shard.with_each_shard(associated_shards) do # split up the other settings by course id if id_map["assignment"] Assignment.where(:id => id_map["assignment"]).pluck(:id, :context_id).each do |a_id, course_id| @@ -241,7 +241,7 @@ def reorganize_gradebook_preferences new_gb_prefs = {} current_gb_prefs.each do |local_course_id, value| # we don't know exactly which shard it was set for, so just set it for them all associated shards - self.associated_shards.each do |shard| + associated_shards.each do |shard| new_gb_prefs[Shard.global_id_for(local_course_id, shard)] = value end end diff --git a/app/models/user_profile.rb b/app/models/user_profile.rb index 8cf0180490a60..c92882912f738 100644 --- a/app/models/user_profile.rb +++ b/app/models/user_profile.rb @@ -154,7 +154,7 @@ def insert_lti_tool_tabs(tabs, user, opts) end def show_lti_tab?(tab, user, account) - tab[:visibility] != 'admins' || self.grants_right?(user, account, :view_lti_tool) + tab[:visibility] != 'admins' || grants_right?(user, account, :view_lti_tool) end def insert_observer_tabs(tabs, user) diff --git a/app/models/user_service.rb b/app/models/user_service.rb index 98eac763f10bd..8abaddce70c79 100644 --- a/app/models/user_service.rb +++ b/app/models/user_service.rb @@ -32,30 +32,30 @@ class UserService < ActiveRecord::Base after_save :clear_cache_key def should_have_communication_channel? - [CommunicationChannel::TYPE_TWITTER].include?(service) && self.user + [CommunicationChannel::TYPE_TWITTER].include?(service) && user end def assert_relations if should_have_communication_channel? - cc = self.user.communication_channels.where(path_type: service).first_or_initialize + cc = user.communication_channels.where(path_type: service).first_or_initialize cc.path_type = service cc.workflow_state = 'active' - cc.path = "#{self.service_user_id}@#{service}.com" + cc.path = "#{service_user_id}@#{service}.com" cc.save! end - if self.user_id && self.service - UserService.where(:user_id => self.user_id, :service => self.service).where("id<>?", self).delete_all + if user_id && service + UserService.where(:user_id => user_id, :service => service).where("id<>?", self).delete_all end true end def clear_cache_key - self.user.clear_cache_key(:user_services) + user.clear_cache_key(:user_services) end def assert_communication_channel # why is twitter getting special treatment? - self.touch if should_have_communication_channel? && !self.user.communication_channels.where(path_type: CommunicationChannel::TYPE_TWITTER).first + touch if should_have_communication_channel? && !user.communication_channels.where(path_type: CommunicationChannel::TYPE_TWITTER).first end def infer_defaults @@ -82,7 +82,7 @@ def infer_defaults scope :visible, -> { where("visible") } def service_name - self.service.titleize rescue "" + service.titleize rescue "" end def password=(password) @@ -90,9 +90,9 @@ def password=(password) end def decrypted_password - return nil unless self.password_salt && self.crypted_password + return nil unless password_salt && crypted_password - Canvas::Security.decrypt_password(self.crypted_password, self.password_salt, 'instructure_user_service') + Canvas::Security.decrypt_password(crypted_password, password_salt, 'instructure_user_service') end def self.register(opts = {}) diff --git a/app/models/web_conference.rb b/app/models/web_conference.rb index 54cd580b96ad7..561378f0d9f3b 100644 --- a/app/models/web_conference.rb +++ b/app/models/web_conference.rb @@ -220,7 +220,7 @@ def course_broadcast_data end on_create_send_to_streams do - [self.user_id] + self.web_conference_participants.map(&:user_id) + [user_id] + web_conference_participants.map(&:user_id) end def context_is_available? @@ -237,14 +237,14 @@ def context_is_available? def add_user(user, type) return unless user - p = self.web_conference_participants.where(user_id: user).first - p ||= self.web_conference_participants.build(user: user) + p = web_conference_participants.where(user_id: user).first + p ||= web_conference_participants.build(user: user) p.participation_type = type unless type == 'attendee' && p.participation_type == 'initiator' (@new_participants ||= []) << user if p.new_record? # Once anyone starts attending the conference, mark it as started. if type == 'attendee' self.started_at ||= Time.now - self.save + save end p.save end @@ -283,7 +283,7 @@ def add_attendee(user) end def context_code - read_attribute(:context_code) || "#{self.context_type.underscore}_#{self.context_id}" rescue nil + read_attribute(:context_code) || "#{context_type.underscore}_#{context_id}" rescue nil end def infer_conference_settings; end @@ -306,19 +306,19 @@ def conference_type=(val) def infer_conference_details infer_conference_settings self.conference_type ||= config && config[:conference_type] - self.context_code = "#{self.context_type.underscore}_#{self.context_id}" rescue nil + self.context_code = "#{context_type.underscore}_#{context_id}" rescue nil self.added_user_ids ||= "" - self.title ||= self.context.is_a?(Course) ? t('#web_conference.default_name_for_courses', "Course Web Conference") : t('#web_conference.default_name_for_groups', "Group Web Conference") + self.title ||= context.is_a?(Course) ? t('#web_conference.default_name_for_courses', "Course Web Conference") : t('#web_conference.default_name_for_groups', "Group Web Conference") self.start_at ||= self.started_at - self.end_at ||= self.ended_at - self.end_at ||= self.start_at + self.duration.minutes if self.start_at && self.duration - if self.started_at && self.ended_at && self.ended_at < self.started_at + self.end_at ||= ended_at + self.end_at ||= self.start_at + duration.minutes if self.start_at && duration + if self.started_at && ended_at && ended_at < self.started_at self.ended_at = self.started_at end end def initiator - self.user + user end def available? @@ -326,7 +326,7 @@ def available? end def finished? - self.started_at && !self.active? + self.started_at && !active? end def long_running? @@ -352,10 +352,10 @@ def running_time def restart self.start_at ||= Time.now - self.end_at = self.duration && (self.start_at + self.duration_in_seconds) + self.end_at = duration && (self.start_at + duration_in_seconds) self.started_at ||= self.start_at self.ended_at = nil - self.save + save end # Default implementation since most implementations don't support scheduling yet @@ -370,9 +370,9 @@ def scheduled_date def active?(force_check = false, allow_check = true) unless force_check - return false if self.ended_at && Time.now > self.ended_at + return false if ended_at && Time.now > ended_at return true if self.start_at && (self.end_at.nil? || (self.end_at && Time.now > self.start_at && Time.now < self.end_at)) - return true if self.ended_at && Time.now < self.ended_at + return true if ended_at && Time.now < ended_at return @conference_active unless @conference_active.nil? end unless allow_check @@ -386,19 +386,19 @@ def active?(force_check = false, allow_check = true) # based on the start time and duration if @conference_active && !self.end_at && !long_running? self.start_at ||= Time.now - self.end_at = [self.start_at, Time.now].compact.min + self.duration_in_seconds - self.save + self.end_at = [self.start_at, Time.now].compact.min + duration_in_seconds + save # If the conference is still active but it's been more than fifteen minutes # since it was supposed to end, just go ahead and end it - elsif @conference_active && self.end_at && self.end_at < 15.minutes.ago && !self.ended_at + elsif @conference_active && self.end_at && self.end_at < 15.minutes.ago && !ended_at self.ended_at = Time.now self.start_at ||= self.started_at - self.end_at ||= self.ended_at + self.end_at ||= ended_at @conference_active = false - self.save + save # If the conference is no longer in use and its end_at has passed, # consider it ended - elsif @conference_active == false && self.started_at && self.end_at && self.end_at < Time.now && !self.ended_at + elsif @conference_active == false && self.started_at && self.end_at && self.end_at < Time.now && !ended_at close end @conference_active @@ -420,7 +420,7 @@ def presenter_key end def attendee_key - @attendee_key ||= self.conference_key + @attendee_key ||= conference_key end # Default implementaiton since not every conference type requires initiation @@ -436,7 +436,7 @@ def recordings def craft_url(user = nil, session = nil, return_to = "http://www.instructure.com") user ||= self.user (initiate_conference and touch) or return nil - if user == self.user || self.grants_right?(user, session, :initiate) + if user == self.user || grants_right?(user, session, :initiate) admin_join_url(user, return_to) else participant_join_url(user, return_to) @@ -454,19 +454,19 @@ def has_advanced_settings scope :after, lambda { |date| where("web_conferences.start_at IS NULL OR web_conferences.start_at>?", date) } set_policy do - given { |user, session| self.users.include?(user) && self.context.grants_right?(user, session, :read) } + given { |user, session| users.include?(user) && context.grants_right?(user, session, :read) } can :read and can :join - given { |user, session| self.users.include?(user) && self.context.grants_right?(user, session, :read) && long_running? && active? } + given { |user, session| users.include?(user) && context.grants_right?(user, session, :read) && long_running? && active? } can :resume - given { |user, session| self.context.grants_right?(user, session, :create_conferences) } + given { |user, session| context.grants_right?(user, session, :create_conferences) } can :create - given { |user, session| user && user.id == self.user_id && self.context.grants_right?(user, session, :create_conferences) } + given { |user, session| user && user.id == user_id && context.grants_right?(user, session, :create_conferences) } can :initiate and can :close - given { |user, session| self.context.grants_all_rights?(user, session, :manage_content, :create_conferences) } + given { |user, session| context.grants_all_rights?(user, session, :manage_content, :create_conferences) } can :read and can :join and can :initiate and can :delete and can :close and can :manage_recordings given { |user, session| context.grants_all_rights?(user, session, :manage_content, :create_conferences) && !finished? } @@ -506,7 +506,7 @@ def as_json(options = {}) end def user_ids - self.web_conference_participants.pluck(:user_id) + web_conference_participants.pluck(:user_id) end def self.conference_types(context) @@ -551,7 +551,7 @@ def self.plugin_types plugins.filter_map { |plugin| next unless plugin.enabled? && (klass = (plugin.base || "#{plugin.id.classify}Conference").constantize rescue nil) && - klass < self.base_class + klass < base_class plugin.settings.merge( :conference_type => plugin.id.classify, @@ -576,11 +576,11 @@ def self.serialization_excludes end def set_root_account_id - case self.context + case context when Course, Group - self.root_account_id = self.context.root_account_id + self.root_account_id = context.root_account_id when Account - self.root_account_id = self.context.resolved_root_account_id + self.root_account_id = context.resolved_root_account_id end end end diff --git a/app/models/web_zip_export.rb b/app/models/web_zip_export.rb index 86fb8c8d715cd..313ac569ecee5 100644 --- a/app/models/web_zip_export.rb +++ b/app/models/web_zip_export.rb @@ -43,7 +43,7 @@ def generate # WebZip Exportable overrides def content_cartridge - self.content_export.attachment + content_export.attachment end def convert_to_offline_web_zip diff --git a/app/models/wiki.rb b/app/models/wiki.rb index 392e2ed28df10..dbf5897e67992 100644 --- a/app/models/wiki.rb +++ b/app/models/wiki.rb @@ -33,7 +33,7 @@ class Wiki < ActiveRecord::Base DEFAULT_FRONT_PAGE_URL = 'front-page' def set_has_no_front_page_default - if self.has_no_front_page.nil? + if has_no_front_page.nil? self.has_no_front_page = true end end @@ -50,7 +50,7 @@ def can_update_front_page_for_master_courses? end def set_downstream_change_for_master_courses - if self.saved_change_to_front_page_url? && !@child_tag_for_import + if saved_change_to_front_page_url? && !@child_tag_for_import child_tag = MasterCourses::ChildContentTag.where(content: self).first if child_tag child_tag.downstream_changes = ["front_page_url"] @@ -60,23 +60,23 @@ def set_downstream_change_for_master_courses end def update_contexts - self.context.try(:touch) + context.try(:touch) end def to_atom Atom::Entry.new do |entry| - entry.title = self.title - entry.updated = self.updated_at - entry.published = self.created_at + entry.title = title + entry.updated = updated_at + entry.published = created_at entry.links << Atom::Link.new(:rel => 'alternate', - :href => "/wikis/#{self.id}") + :href => "/wikis/#{id}") end end def update_default_wiki_page_roles(new_roles, old_roles) return if new_roles == old_roles - self.wiki_pages.each do |p| + wiki_pages.each do |p| if p.editing_roles == old_roles p.editing_roles = new_roles p.save @@ -85,48 +85,48 @@ def update_default_wiki_page_roles(new_roles, old_roles) end def front_page - url = self.get_front_page_url + url = get_front_page_url return nil if url.nil? # TODO i18n t :front_page_name, "Front Page" # attempt to find the page and store it's url (if it is found) - page = self.wiki_pages.not_deleted.where(url: url).first - self.set_front_page_url!(url) if self.has_no_front_page && page + page = wiki_pages.not_deleted.where(url: url).first + set_front_page_url!(url) if has_no_front_page && page # return an implicitly created page if a page could not be found - page ||= self.wiki_pages.temp_record(:title => url.titleize, :url => url, :context => self.context) + page ||= wiki_pages.temp_record(:title => url.titleize, :url => url, :context => context) page end def has_front_page? - !self.has_no_front_page + !has_no_front_page end def get_front_page_url - self.front_page_url || DEFAULT_FRONT_PAGE_URL if self.has_front_page? + front_page_url || DEFAULT_FRONT_PAGE_URL if has_front_page? end def unset_front_page! - if self.context.is_a?(Course) && self.context.default_view == 'wiki' - self.context.default_view = nil - self.context.save + if context.is_a?(Course) && context.default_view == 'wiki' + context.default_view = nil + context.save end - self.front_page.touch if self.front_page&.persisted? + front_page.touch if front_page&.persisted? self.front_page_url = nil self.has_no_front_page = true - self.save + save end def set_front_page_url!(url) return false if url.blank? - return true if self.has_front_page? && self.front_page_url == url + return true if has_front_page? && front_page_url == url self.has_no_front_page = false self.front_page_url = url - self.save + save end def context @@ -144,33 +144,33 @@ def context_type delegate :id, to: :context, prefix: true set_policy do - given { |user, session| self.context.grants_right?(user, session, :read) } + given { |user, session| context.grants_right?(user, session, :read) } can :read - given { |user, session| self.context.grants_right?(user, session, :view_unpublished_items) } + given { |user, session| context.grants_right?(user, session, :view_unpublished_items) } can :view_unpublished_items - given { |user, session| self.context.grants_right?(user, session, :participate_as_student) && self.context.respond_to?(:allow_student_wiki_edits) && self.context.allow_student_wiki_edits } + given { |user, session| context.grants_right?(user, session, :participate_as_student) && context.respond_to?(:allow_student_wiki_edits) && context.allow_student_wiki_edits } can :read and can :create_page and can :update_page given do |user, session| - self.context.grants_right?(user, session, :manage_wiki_create) + context.grants_right?(user, session, :manage_wiki_create) end can :read and can :create_page and can :view_unpublished_items given do |user, session| - self.context.grants_right?(user, session, :manage_wiki_delete) + context.grants_right?(user, session, :manage_wiki_delete) end can :read and can :delete_page and can :view_unpublished_items given do |user, session| - self.context.grants_right?(user, session, :manage_wiki_update) + context.grants_right?(user, session, :manage_wiki_update) end can :read and can :update and can :update_page and can :view_unpublished_items # Pages created by a user without this permission will be automatically published given do |user, session| - self.context.grants_right?(user, session, :manage_wiki_update) && !self.context.is_a?(Group) + context.grants_right?(user, session, :manage_wiki_update) && !context.is_a?(Group) end can :publish_page end @@ -187,7 +187,7 @@ def self.wiki_for_context(context) t :default_course_wiki_name, "%{course_name} Wiki", :course_name => nil t :default_group_wiki_name, "%{group_name} Wiki", :group_name => nil - self.extend TextHelper + extend TextHelper name = CanvasTextHelper.truncate_text(context.name, { :max_length => 200, :ellipsis => '' }) context.wiki = wiki = Wiki.create!(:title => "#{name} Wiki", :root_account_id => context.root_account_id) @@ -203,10 +203,10 @@ def build_wiki_page(user, opts = {}) opts[:url] = opts[:title].to_s.to_url if opts.include?(:title) end - self.shard.activate do + shard.activate do page = WikiPage.new(opts) page.wiki = self - page.context = self.context + page.context = context page.initialize_wiki_page(user) page end @@ -215,13 +215,13 @@ def build_wiki_page(user, opts = {}) def find_page(param, include_deleted: false) # to allow linking to a WikiPage by id (to avoid needing to hit the database to pull its url) if (match = param.match(/\Apage_id:(\d+)\z/)) - return self.wiki_pages.where(id: match[1].to_i).first + return wiki_pages.where(id: match[1].to_i).first end scope = if include_deleted - self.wiki_pages.order(Arel.sql("CASE WHEN workflow_state <> 'deleted' THEN 0 ELSE 1 END")) + wiki_pages.order(Arel.sql("CASE WHEN workflow_state <> 'deleted' THEN 0 ELSE 1 END")) else - self.wiki_pages.not_deleted + wiki_pages.not_deleted end scope.where(url: [param.to_s, param.to_url]).first || scope.where(id: param.to_i).first end diff --git a/app/models/wiki_page.rb b/app/models/wiki_page.rb index ba7895997509a..c1ed1e7052114 100644 --- a/app/models/wiki_page.rb +++ b/app/models/wiki_page.rb @@ -58,7 +58,7 @@ class WikiPage < ActiveRecord::Base validate :validate_front_page_visibility before_save :default_submission_values, - if: proc { self.context.try(:feature_enabled?, :conditional_release) } + if: proc { context.try(:feature_enabled?, :conditional_release) } before_save :set_revised_at before_validation :ensure_wiki_and_context before_validation :ensure_unique_title @@ -66,7 +66,7 @@ class WikiPage < ActiveRecord::Base after_save :touch_context after_save :update_assignment, - if: proc { self.context.try(:feature_enabled?, :conditional_release) } + if: proc { context.try(:feature_enabled?, :conditional_release) } scope :starting_with_title, lambda { |title| where('title ILIKE ?', "#{title}%") @@ -93,7 +93,7 @@ class WikiPage < ActiveRecord::Base self.ignored_columns = %i[view_count] def ensure_wiki_and_context - self.wiki_id ||= (self.context.wiki_id || self.context.wiki.id) + self.wiki_id ||= (context.wiki_id || context.wiki.id) end def context @@ -109,12 +109,12 @@ def context end def touch_context - self.context.touch + context.touch end def validate_front_page_visibility - if !published? && self.is_front_page? - self.errors.add(:published, t(:cannot_unpublish_front_page, "cannot unpublish front page")) + if !published? && is_front_page? + errors.add(:published, t(:cannot_unpublish_front_page, "cannot unpublish front page")) end end @@ -122,17 +122,17 @@ def ensure_unique_title return if deleted? to_cased_title = ->(string) { string.gsub(/[^\w]+/, " ").gsub(/\b('?[a-z])/) { $1.capitalize }.strip } - self.title ||= to_cased_title.call(self.url || "page") + self.title ||= to_cased_title.call(url || "page") # TODO i18n (see wiki.rb) - if self.title == "Front Page" && self.new_record? - baddies = self.context.wiki_pages.not_deleted.where(title: "Front Page").reject { |p| p.url == "front-page" } + if self.title == "Front Page" && new_record? + baddies = context.wiki_pages.not_deleted.where(title: "Front Page").reject { |p| p.url == "front-page" } baddies.each { |p| p.title = to_cased_title.call(p.url) p.save_without_broadcasting! } end - if self.context.wiki_pages.not_deleted.where(title: self.title).where.not(:id => self.id).first + if context.wiki_pages.not_deleted.where(title: self.title).where.not(:id => id).first real_title = self.title.gsub(/-(\d*)\z/, '') # remove any "-#" at the end n = $1 ? $1.to_i + 1 : 2 new_title = nil @@ -155,15 +155,15 @@ def ensure_unique_url return if deleted? url_attribute = self.class.url_attribute - base_url = self.send(url_attribute) - base_url = self.send(self.class.attribute_to_urlify).to_s.to_url if base_url.blank? || !self.only_when_blank + base_url = send(url_attribute) + base_url = send(self.class.attribute_to_urlify).to_s.to_url if base_url.blank? || !only_when_blank conditions = [wildcard(url_attribute.to_s, base_url, :type => :right)] unless new_record? conditions.first << " and id != ?" conditions << id end - urls = self.context.wiki_pages.where(*conditions).not_deleted.pluck(:url) + urls = context.wiki_pages.where(*conditions).not_deleted.pluck(:url) # This is the part in stringex that messed us up, since it will never allow # a url of "front-page" once "front-page-1" or "front-page-2" is created # We modify it to allow "front-page" and start the indexing at "front-page-2" @@ -180,7 +180,7 @@ def ensure_unique_url end sanitize_field :body, CanvasSanitize::SANITIZE - copy_authorized_links(:body) { [self.context, self.user] } + copy_authorized_links(:body) { [context, user] } validates_each :title do |record, attr, value| if value.blank? @@ -218,8 +218,8 @@ def ensure_unique_url def set_revised_at self.revised_at ||= Time.now - self.revised_at = Time.now if self.body_changed? || self.title_changed? - @page_changed = self.body_changed? || self.title_changed? + self.revised_at = Time.now if body_changed? || title_changed? + @page_changed = body_changed? || title_changed? true end @@ -238,7 +238,7 @@ def remove_changed_flag end def version_history - self.versions.map(&:model) + versions.map(&:model) end scope :deleted_last, -> { order(Arel.sql("workflow_state='deleted'")) } @@ -256,7 +256,7 @@ def not_deleted scope :order_by_id, -> { order(:id) } def low_level_locked_for?(user, opts = {}) - return false unless self.could_be_locked + return false unless could_be_locked RequestCache.cache(locked_request_cache_key(user), opts[:deep_check_if_needed]) do locked = false @@ -270,52 +270,52 @@ def low_level_locked_for?(user, opts = {}) end def is_front_page? - return false if self.deleted? + return false if deleted? - self.url == self.wiki.get_front_page_url # wiki.get_front_page_url checks has_front_page? + url == wiki.get_front_page_url # wiki.get_front_page_url checks has_front_page? end def set_as_front_page! - if self.unpublished? - self.errors.add(:front_page, t(:cannot_set_unpublished_front_page, 'could not set as front page because it is unpublished')) + if unpublished? + errors.add(:front_page, t(:cannot_set_unpublished_front_page, 'could not set as front page because it is unpublished')) return false end - self.wiki.set_front_page_url!(self.url) - self.touch if self.persisted? + wiki.set_front_page_url!(url) + touch if persisted? end def context_module_tag_for(context) - @tag ||= self.context_module_tags.where(context_id: context, context_type: context.class.base_class.name).first + @tag ||= context_module_tags.where(context_id: context, context_type: context.class.base_class.name).first end def context_module_action(user, context, action) - self.context_module_tags.where(context_id: context, context_type: context.class.base_class.name).each do |tag| + context_module_tags.where(context_id: context, context_type: context.class.base_class.name).each do |tag| tag.context_module_action(user, action) end end set_policy do - given { |user, session| self.can_read_page?(user, session) } + given { |user, session| can_read_page?(user, session) } can :read - given { |user| user && self.can_edit_page?(user) } + given { |user| user && can_edit_page?(user) } can :update_content and can :read_revisions - given { |user, session| user && self.wiki.grants_right?(user, session, :create_page) } + given { |user, session| user && wiki.grants_right?(user, session, :create_page) } can :create - given { |user, session| user && self.can_edit_page?(user) && self.wiki.grants_right?(user, session, :update_page) } + given { |user, session| user && can_edit_page?(user) && wiki.grants_right?(user, session, :update_page) } can :update and can :read_revisions - given { |user, session| user && can_read_page?(user) && self.wiki.grants_right?(user, session, :delete_page) } + given { |user, session| user && can_read_page?(user) && wiki.grants_right?(user, session, :delete_page) } can :delete end def can_read_page?(user, session = nil) - return true if self.unpublished? && self.wiki.grants_right?(user, session, :view_unpublished_items) + return true if unpublished? && wiki.grants_right?(user, session, :view_unpublished_items) - self.published? && self.wiki.grants_right?(user, session, :read) + published? && wiki.grants_right?(user, session, :read) end def can_edit_page?(user, session = nil) @@ -377,7 +377,7 @@ def course_broadcast_data def participants res = [] if context&.available? - res += if !self.active? + res += if !active? context.participating_admins else context.participants(by_date: true) @@ -396,12 +396,12 @@ def to_atom(opts = {}) Atom::Entry.new do |entry| entry.title = t(:atom_entry_title, "Wiki Page, %{course_or_group_name}: %{page_title}", :course_or_group_name => context.name, :page_title => self.title) entry.authors << Atom::Person.new(:name => t(:atom_author, "Wiki Page")) - entry.updated = self.updated_at - entry.published = self.created_at - entry.id = "tag:#{HostUrl.default_host},#{self.created_at.strftime("%Y-%m-%d")}:/wiki_pages/#{self.feed_code}_#{self.updated_at.strftime("%Y-%m-%d")}" + entry.updated = updated_at + entry.published = created_at + entry.id = "tag:#{HostUrl.default_host},#{created_at.strftime("%Y-%m-%d")}:/wiki_pages/#{feed_code}_#{updated_at.strftime("%Y-%m-%d")}" entry.links << Atom::Link.new(:rel => 'alternate', - :href => "http://#{HostUrl.context_host(context)}/#{self.context.class.to_s.downcase.pluralize}/#{self.context.id}/pages/#{self.url}") - entry.content = Atom::Content::Html.new(self.body || t('defaults.no_content', "no content")) + :href => "http://#{HostUrl.context_host(context)}/#{self.context.class.to_s.downcase.pluralize}/#{self.context.id}/pages/#{url}") + entry.content = Atom::Content::Html.new(body || t('defaults.no_content', "no content")) end end @@ -414,7 +414,7 @@ def to_param end def last_revision_at - res = self.revised_at || self.updated_at + res = self.revised_at || updated_at res = Time.now if res.is_a?(String) res end @@ -466,7 +466,7 @@ def self.reinterpret_version_yaml(yaml_string) # By default, all associated entities are duplicated. def duplicate(opts = {}) # Don't clone a new record - return self if self.new_record? + return self if new_record? default_opts = { :duplicate_assignment => true, @@ -477,20 +477,20 @@ def duplicate(opts = {}) :title => opts_with_default[:copy_title] || get_copy_title(self, t("Copy"), self.title), :wiki_id => self.wiki_id, - :context_id => self.context_id, - :context_type => self.context_type, - :body => self.body, + :context_id => context_id, + :context_type => context_type, + :body => body, :workflow_state => "unpublished", - :user_id => self.user_id, - :protected_editing => self.protected_editing, - :editing_roles => self.editing_roles, - :todo_date => self.todo_date + :user_id => user_id, + :protected_editing => protected_editing, + :editing_roles => editing_roles, + :todo_date => todo_date }) - if self.assignment && opts_with_default[:duplicate_assignment] - result.assignment = self.assignment.duplicate({ - :duplicate_wiki_page => false, - :copy_title => result.title - }) + if assignment && opts_with_default[:duplicate_assignment] + result.assignment = assignment.duplicate({ + :duplicate_wiki_page => false, + :copy_title => result.title + }) end result end @@ -520,7 +520,7 @@ def initialize_wiki_page(user) def post_to_pandapub_when_revised if saved_change_to_revised_at? CanvasPandaPub.post_update( - "/private/wiki_page/#{self.global_id}/update", { + "/private/wiki_page/#{global_id}/update", { revised_at: self.revised_at } ) @@ -528,6 +528,6 @@ def post_to_pandapub_when_revised end def set_root_account_id - self.root_account_id = self.context&.root_account_id unless self.root_account_id + self.root_account_id = context&.root_account_id unless root_account_id end end diff --git a/app/observers/stream_item_cache.rb b/app/observers/stream_item_cache.rb index cdda0a8500bd9..79177094ead08 100644 --- a/app/observers/stream_item_cache.rb +++ b/app/observers/stream_item_cache.rb @@ -33,14 +33,14 @@ def invalidate_recent_stream_items(stream_instance) end def self.invalidate_recent_stream_items(user_id, context_type, context_id) - dashboard_key = self.recent_stream_items_key(user_id) - context_key = self.recent_stream_items_key(user_id, context_type, context_id) + dashboard_key = recent_stream_items_key(user_id) + context_key = recent_stream_items_key(user_id, context_type, context_id) Rails.cache.delete dashboard_key Rails.cache.delete context_key end def self.invalidate_all_recent_stream_items(user_ids, context_type, context_id) - user_ids.each { |user_id| self.invalidate_recent_stream_items(user_id, context_type, context_id) } + user_ids.each { |user_id| invalidate_recent_stream_items(user_id, context_type, context_id) } end def self.invalidate_context_stream_item_key(context_type, context_id) diff --git a/config/application.rb b/config/application.rb index 7b2b5b3dabdcd..640d9632ed0d6 100644 --- a/config/application.rb +++ b/config/application.rb @@ -340,7 +340,7 @@ def key_generator initializer "canvas.init_credentials", before: "active_record.initialize_database" do self.credentials = Canvas::Credentials.new(credentials) # Ensure we load credentials at initailization time to avoid overloading vault - self.credentials.config + credentials.config end # we don't know what middleware to make SessionsTimeout follow until after diff --git a/config/initializers/active_record.rb b/config/initializers/active_record.rb index 1551004a7fd5a..b5d1aa1bcf696 100644 --- a/config/initializers/active_record.rb +++ b/config/initializers/active_record.rb @@ -91,7 +91,7 @@ def serializable_add_includes(options = {}) end def feed_code - id = self.uuid rescue self.id + id = uuid rescue self.id "#{self.class.reflection_type_name}_#{id}" end @@ -158,7 +158,7 @@ def self.convert_class_name(str) end def self.asset_string(id) - "#{self.reflection_type_name}_#{id}" + "#{reflection_type_name}_#{id}" end def asset_string @@ -188,7 +188,7 @@ def self.define_asset_string_backcompat_method(string_version_name, association_ unless method # this is weird, but gets the instance methods defined so they can be chained begin - self.new.send("#{association_version_name}_id") + new.send("#{association_version_name}_id") rescue # the db doesn't exist yet; no need to bother with backcompat methods anyway return @@ -217,7 +217,7 @@ def export_columns end def to_row - export_columns.map { |c| self.send(c) } + export_columns.map { |c| send(c) } end def is_a_context? @@ -225,10 +225,10 @@ def is_a_context? end def cached_context_short_name - if self.respond_to?(:context) - code = self.respond_to?(:context_code) ? self.context_code : self.context.asset_string + if respond_to?(:context) + code = respond_to?(:context_code) ? context_code : context.asset_string @cached_context_name ||= Rails.cache.fetch(['short_name_lookup', code].cache_key) do - self.context.short_name rescue "" + context.short_name rescue "" end else raise "Can only call cached_context_short_name on items with a context" @@ -241,16 +241,16 @@ def self.skip_touch_context(skip = true) def save_without_touching_context @skip_touch_context = true - self.save + save @skip_touch_context = false end def touch_context return if @@skip_touch_context ||= false || @skip_touch_context ||= false - if self.respond_to?(:context_type) && self.respond_to?(:context_id) && self.context_type && self.context_id + if respond_to?(:context_type) && respond_to?(:context_id) && context_type && context_id self.class.connection.after_transaction_commit do - self.context_type.constantize.where(id: self.context_id).update_all(updated_at: Time.now.utc) + context_type.constantize.where(id: context_id).update_all(updated_at: Time.now.utc) end end rescue @@ -258,9 +258,9 @@ def touch_context end def touch_user - if self.respond_to?(:user_id) && self.user_id + if respond_to?(:user_id) && user_id User.connection.after_transaction_commit do - User.where(:id => self.user_id).update_all(:updated_at => Time.now.utc) + User.where(:id => user_id).update_all(:updated_at => Time.now.utc) end end true @@ -270,7 +270,7 @@ def touch_user end def context_url_prefix - "#{self.context_type.downcase.pluralize}/#{self.context_id}" + "#{context_type.downcase.pluralize}/#{context_id}" end # Example: @@ -278,18 +278,18 @@ def context_url_prefix def as_json(options = nil) options = options.try(:dup) || {} - self.set_serialization_options if self.respond_to?(:set_serialization_options) + set_serialization_options if respond_to?(:set_serialization_options) except = options.delete(:except) || [] except = Array(except).dup except.concat(self.class.serialization_excludes) if self.class.respond_to?(:serialization_excludes) - except.concat(self.serialization_excludes) if self.respond_to?(:serialization_excludes) + except.concat(serialization_excludes) if respond_to?(:serialization_excludes) except.uniq! methods = options.delete(:methods) || [] methods = Array(methods).dup methods.concat(self.class.serialization_methods) if self.class.respond_to?(:serialization_methods) - methods.concat(self.serialization_methods) if self.respond_to?(:serialization_methods) + methods.concat(serialization_methods) if respond_to?(:serialization_methods) methods.uniq! options[:except] = except unless except.empty? @@ -312,19 +312,19 @@ def as_json(options = nil) if options[:permissions] obj_hash = options[:include_root] ? hash[self.class.base_class.model_name.element] : hash - if self.respond_to?(:filter_attributes_for_user) - self.filter_attributes_for_user(obj_hash, options[:permissions][:user], options[:permissions][:session]) + if respond_to?(:filter_attributes_for_user) + filter_attributes_for_user(obj_hash, options[:permissions][:user], options[:permissions][:session]) end unless options[:permissions][:include_permissions] == false - permissions_hash = self.rights_status(options[:permissions][:user], options[:permissions][:session], *options[:permissions][:policies]) - if self.respond_to?(:serialize_permissions) - permissions_hash = self.serialize_permissions(permissions_hash, options[:permissions][:user], options[:permissions][:session]) + permissions_hash = rights_status(options[:permissions][:user], options[:permissions][:session], *options[:permissions][:policies]) + if respond_to?(:serialize_permissions) + permissions_hash = serialize_permissions(permissions_hash, options[:permissions][:user], options[:permissions][:session]) end obj_hash["permissions"] = permissions_hash end end - self.revert_from_serialization_options if self.respond_to?(:revert_from_serialization_options) + revert_from_serialization_options if respond_to?(:revert_from_serialization_options) hash.with_indifferent_access end @@ -619,7 +619,7 @@ def self.unique_constraint_retry(retries = 1) def self.current_xlog_location Shard.current(shard_category).database_server.unguard do GuardRail.activate(:primary) do - if Rails.env.test? ? self.in_transaction_in_test? : connection.open_transactions > 0 + if Rails.env.test? ? in_transaction_in_test? : connection.open_transactions > 0 raise "don't run current_xlog_location in a transaction" else connection.current_wal_lsn @@ -666,17 +666,17 @@ def self.bulk_insert(records) array_columns = records.first.select { |_k, v| v.is_a?(Array) }.keys array_columns.each do |column_name| - cast_type = connection.send(:lookup_cast_type_from_column, self.columns_hash[column_name.to_s]) + cast_type = connection.send(:lookup_cast_type_from_column, columns_hash[column_name.to_s]) records.each do |row| row[column_name] = cast_type.serialize(row[column_name]) end end - if self.respond_to?(:attrs_in_partition_groups) + if respond_to?(:attrs_in_partition_groups) # this model is partitioned, we need to send a separate # insert statement for each partition represented # in the input records - self.attrs_in_partition_groups(records) do |partition_name, partition_records| + attrs_in_partition_groups(records) do |partition_name, partition_records| transaction do connection.bulk_insert(partition_name, partition_records) end @@ -691,8 +691,8 @@ def self.bulk_insert(records) include ActiveSupport::Callbacks::Suspension def self.touch_all_records - self.find_ids_in_ranges do |min_id, max_id| - self.where(primary_key => min_id..max_id).touch_all + find_ids_in_ranges do |min_id, max_id| + where(primary_key => min_id..max_id).touch_all end end @@ -1195,7 +1195,7 @@ def update_all_locked_in_order(updates) end def touch_all - self.activate do |relation| + activate do |relation| relation.update_all_locked_in_order(updated_at: Time.now.utc) end end @@ -1523,7 +1523,7 @@ def runnable? def load_migration load(filename) @migration = name.constantize - raise "#{self.name} (#{self.version}) is not tagged as exactly one of predeploy or postdeploy!" unless (@migration.tags & ActiveRecord::Migration::DEPLOY_TAGS).length == 1 + raise "#{name} (#{version}) is not tagged as exactly one of predeploy or postdeploy!" unless (@migration.tags & ActiveRecord::Migration::DEPLOY_TAGS).length == 1 @migration end @@ -1762,7 +1762,7 @@ def skip_touch_callbacks(name) def touch_callbacks_skipped?(name) @skip_touch_callbacks&.include?(name) || - (self.superclass < ActiveRecord::Base && self.superclass.touch_callbacks_skipped?(name)) + (superclass < ActiveRecord::Base && superclass.touch_callbacks_skipped?(name)) end end @@ -1859,7 +1859,7 @@ def explain(analyze: false) yield else # fold in switchman's override - self.activate { |relation| relation.send(:exec_queries) } + activate { |relation| relation.send(:exec_queries) } end end, analyze: analyze) end diff --git a/config/initializers/active_support.rb b/config/initializers/active_support.rb index 848fdd4055aa4..61001093734de 100644 --- a/config/initializers/active_support.rb +++ b/config/initializers/active_support.rb @@ -20,7 +20,7 @@ ActiveSupport::TimeWithZone.delegate :to_yaml, :to => :utc ActiveSupport::SafeBuffer.class_eval do def encode_with(coder) - coder.scalar("!str", self.to_str) + coder.scalar("!str", to_str) end end diff --git a/config/initializers/folio.rb b/config/initializers/folio.rb index 81b9d5e07c97d..b8f26e594ac00 100644 --- a/config/initializers/folio.rb +++ b/config/initializers/folio.rb @@ -23,11 +23,11 @@ module Folio::WillPaginate::ActiveRecord::Pagination def paginate(options = {}) unless options.key?(:total_entries) scope = if ::Rails.version < '4' - self.scoped - elsif self.is_a?(::ActiveRecord::Relation) + scoped + elsif is_a?(::ActiveRecord::Relation) self elsif self < ::ActiveRecord::Base - self.all + all else self.scope end diff --git a/config/initializers/marginalia.rb b/config/initializers/marginalia.rb index dddd789b5b7be..d7fcc776511f7 100644 --- a/config/initializers/marginalia.rb +++ b/config/initializers/marginalia.rb @@ -45,7 +45,7 @@ def job_tag module Marginalia::RakeTask def execute(args = nil) - previous, Marginalia::Comment.rake_task = Marginalia::Comment.rake_task, self.name + previous, Marginalia::Comment.rake_task = Marginalia::Comment.rake_task, name super ensure Marginalia::Comment.rake_task = previous diff --git a/config/initializers/switchman.rb b/config/initializers/switchman.rb index 987e01262f73d..48b52893f45e5 100644 --- a/config/initializers/switchman.rb +++ b/config/initializers/switchman.rb @@ -61,13 +61,13 @@ def settings end def encrypt_settings - s = self.settings.dup + s = settings.dup if (encryption_key = s.delete(:encryption_key)) secret, salt = Canvas::Security.encrypt_password(encryption_key, 'shard_encryption_key') s[:encryption_key_enc] = secret s[:encryption_key_salt] = salt end - if s != self.settings + if s != settings self.settings = s end s diff --git a/config/initializers/time.rb b/config/initializers/time.rb index 917d70cfffd03..0c3ff75f3d39b 100644 --- a/config/initializers/time.rb +++ b/config/initializers/time.rb @@ -35,9 +35,7 @@ def blank? false end - def utc_datetime - self.comparable_time.utc_datetime - end + delegate :utc_datetime, to: :comparable_time end module TimeZoneAsJson diff --git a/db/migrate/20101210192618_init_canvas_db.rb b/db/migrate/20101210192618_init_canvas_db.rb index f8cf65a92447c..c5f712f1e4afe 100644 --- a/db/migrate/20101210192618_init_canvas_db.rb +++ b/db/migrate/20101210192618_init_canvas_db.rb @@ -3223,7 +3223,7 @@ def self.up change_column :schema_migrations, :version, :string, limit: 255 - self.connection.execute <<~SQL.squish + connection.execute <<~SQL.squish CREATE VIEW #{connection.quote_table_name('assignment_student_visibilities')} AS SELECT DISTINCT a.id as assignment_id, e.user_id as user_id, @@ -3279,7 +3279,7 @@ def self.up ) SQL - self.connection.execute <<~SQL.squish + connection.execute <<~SQL.squish CREATE VIEW #{connection.quote_table_name('quiz_student_visibilities')} AS SELECT DISTINCT q.id as quiz_id, e.user_id as user_id, diff --git a/db/migrate/20170815103759_ignore_deleted_submissions_for_assignment_visibility.rb b/db/migrate/20170815103759_ignore_deleted_submissions_for_assignment_visibility.rb index 451f5f5a79b8d..9704480d2fe5b 100644 --- a/db/migrate/20170815103759_ignore_deleted_submissions_for_assignment_visibility.rb +++ b/db/migrate/20170815103759_ignore_deleted_submissions_for_assignment_visibility.rb @@ -22,11 +22,11 @@ class IgnoreDeletedSubmissionsForAssignmentVisibility < ActiveRecord::Migration[ tag :postdeploy def up - self.connection.execute "DROP VIEW #{connection.quote_table_name('assignment_student_visibilities')}" - self.connection.execute "DROP VIEW #{connection.quote_table_name('quiz_student_visibilities')}" + connection.execute "DROP VIEW #{connection.quote_table_name('assignment_student_visibilities')}" + connection.execute "DROP VIEW #{connection.quote_table_name('quiz_student_visibilities')}" # Update the view so submission scores aren't as important as the submission's workflow_state - self.connection.execute %(CREATE VIEW #{connection.quote_table_name('assignment_student_visibilities')} AS + connection.execute %(CREATE VIEW #{connection.quote_table_name('assignment_student_visibilities')} AS SELECT DISTINCT a.id as assignment_id, e.user_id as user_id, c.id as course_id @@ -81,7 +81,7 @@ def up ) ) - self.connection.execute %(CREATE VIEW #{connection.quote_table_name('quiz_student_visibilities')} AS + connection.execute %(CREATE VIEW #{connection.quote_table_name('quiz_student_visibilities')} AS SELECT DISTINCT q.id as quiz_id, e.user_id as user_id, c.id as course_id @@ -132,11 +132,11 @@ def up end def down - self.connection.execute "DROP VIEW #{connection.quote_table_name('assignment_student_visibilities')}" - self.connection.execute "DROP VIEW #{connection.quote_table_name('quiz_student_visibilities')}" + connection.execute "DROP VIEW #{connection.quote_table_name('assignment_student_visibilities')}" + connection.execute "DROP VIEW #{connection.quote_table_name('quiz_student_visibilities')}" # Recreate the old view where submission scores are significant - self.connection.execute %(CREATE VIEW #{connection.quote_table_name('assignment_student_visibilities')} AS + connection.execute %(CREATE VIEW #{connection.quote_table_name('assignment_student_visibilities')} AS SELECT DISTINCT a.id as assignment_id, e.user_id as user_id, c.id as course_id @@ -191,7 +191,7 @@ def down ) ) - self.connection.execute %(CREATE VIEW #{connection.quote_table_name('quiz_student_visibilities')} AS + connection.execute %(CREATE VIEW #{connection.quote_table_name('quiz_student_visibilities')} AS SELECT DISTINCT q.id as quiz_id, e.user_id as user_id, c.id as course_id diff --git a/db/migrate/20171013185152_add_not_null_constraint_to_scores_course_score.rb b/db/migrate/20171013185152_add_not_null_constraint_to_scores_course_score.rb index b2d0ec52ba6ca..aaaa88a81bb12 100644 --- a/db/migrate/20171013185152_add_not_null_constraint_to_scores_course_score.rb +++ b/db/migrate/20171013185152_add_not_null_constraint_to_scores_course_score.rb @@ -23,18 +23,18 @@ class AddNotNullConstraintToScoresCourseScore < ActiveRecord::Migration[5.0] disable_ddl_transaction! def up - self.connection.execute(<=?", position) .update_all("#{self.class.position_column} = (#{self.class.position_column} + 1)") end - self.update_attribute(self.class.position_column, position) + update_attribute(self.class.position_column, position) end end diff --git a/gems/adheres_to_policy/lib/adheres_to_policy/cache.rb b/gems/adheres_to_policy/lib/adheres_to_policy/cache.rb index fb1fb54f55e0e..de1fbb1cd1e61 100644 --- a/gems/adheres_to_policy/lib/adheres_to_policy/cache.rb +++ b/gems/adheres_to_policy/lib/adheres_to_policy/cache.rb @@ -40,7 +40,7 @@ class Cache def self.fetch(key, use_rails_cache: true) return [yield, :bypass_generated] unless key - value, how_it_got_it = self.read(key, use_rails_cache: use_rails_cache) + value, how_it_got_it = read(key, use_rails_cache: use_rails_cache) if value.nil? if block_given? how_it_got_it = :generated @@ -48,7 +48,7 @@ def self.fetch(key, use_rails_cache: true) value = yield elapsed = Time.now - start_time Thread.current[:last_cache_generate] = elapsed # so we can record it in the logs - self.write(key, value, use_rails_cache: use_rails_cache) + write(key, value, use_rails_cache: use_rails_cache) end end diff --git a/gems/adheres_to_policy/spec/adheres_to_policy/instance_methods_spec.rb b/gems/adheres_to_policy/spec/adheres_to_policy/instance_methods_spec.rb index 001b015ddf2fd..9cde8d0c3a7a3 100644 --- a/gems/adheres_to_policy/spec/adheres_to_policy/instance_methods_spec.rb +++ b/gems/adheres_to_policy/spec/adheres_to_policy/instance_methods_spec.rb @@ -488,7 +488,7 @@ def call_permission_cache_key_for(*args) given { |_| true } can :create - given { |u| self.grants_right?(u, :create) } + given { |u| grants_right?(u, :create) } can :update end end @@ -510,7 +510,7 @@ def call_permission_cache_key_for(*args) given { |_| true } can :create - given { |u| self.grants_right?(u, :create) } + given { |u| grants_right?(u, :create) } can :update end end diff --git a/gems/attachment_fu/lib/attachment_fu.rb b/gems/attachment_fu/lib/attachment_fu.rb index 544a23e478913..e4e2b12acceb6 100644 --- a/gems/attachment_fu/lib/attachment_fu.rb +++ b/gems/attachment_fu/lib/attachment_fu.rb @@ -277,16 +277,16 @@ def create_or_update_thumbnail(temp_file, file_name_suffix, *size) end def create_thumbnail_size(target_size) - actual_size = self.attachment_options[:thumbnails][target_size] + actual_size = attachment_options[:thumbnails][target_size] raise "this class doesn't have a thubnail size for #{target_size}" if actual_size.nil? begin - tmp = self.create_temp_file - res = self.create_or_update_thumbnail(tmp, target_size.to_s, actual_size) + tmp = create_temp_file + res = create_or_update_thumbnail(tmp, target_size.to_s, actual_size) rescue Aws::S3::Errors::NoSuchKey => e - logger.warn("error when trying to make thumbnail for attachment_id: #{self.id} (the image probably doesn't exist on s3) error details: #{e.inspect}") + logger.warn("error when trying to make thumbnail for attachment_id: #{id} (the image probably doesn't exist on s3) error details: #{e.inspect}") rescue ThumbnailError => e - logger.warn("error creating thumbnail for attachment_id #{self.id}: #{e.inspect}") + logger.warn("error creating thumbnail for attachment_id #{id}: #{e.inspect}") ensure tmp&.unlink end @@ -311,12 +311,12 @@ def image_size # Returns true if the attachment data will be written to the storage system on the next save def save_attachment? - if self.is_a?(Attachment) - if self.root_attachment_id && self.new_record? + if is_a?(Attachment) + if root_attachment_id && new_record? return false end - self.filename && File.file?(temp_path.to_s) + filename && File.file?(temp_path.to_s) else File.file?(temp_path.to_s) end @@ -341,7 +341,7 @@ def uploaded_data def uploaded_data=(file_data) return if file_data.blank? - if self.is_a?(Attachment) + if is_a?(Attachment) # glean information from the file handle self.content_type = detect_mimetype(file_data) self.filename = file_data.original_filename if respond_to?(:filename) && file_data.respond_to?(:original_filename) @@ -351,19 +351,19 @@ def uploaded_data=(file_data) self.temp_data = file_data.read file_from_path = false else - self.temp_paths.unshift file_data + temp_paths.unshift file_data end # If we're overwriting an existing file, we need to take serious # precautions, since other Attachment records could be using this file. # We first remove any root references for this file, and then we generate # a new unique filename for this file so anybody children of this attachment # will still be able to get at the original. - unless self.new_record? + unless new_record? self.root_attachment = nil self.root_attachment_id = nil self.workflow_state = nil self.filename = filename.sub(/\A\d+_\d+__/, "") - self.filename = "#{Time.now.to_i}_#{rand(999)}__#{self.filename}" if self.filename + self.filename = "#{Time.now.to_i}_#{rand(999)}__#{filename}" if filename end unless attachment_options[:skip_sis] read_bytes = false @@ -371,7 +371,7 @@ def uploaded_data=(file_data) begin io = file_data if file_from_path - io = File.open(self.temp_path, 'rb') + io = File.open(temp_path, 'rb') end io.rewind io.each_line do |line| @@ -405,9 +405,9 @@ def uploaded_data=(file_data) end def find_existing_attachment_for_md5 - self.shard.activate do + shard.activate do GuardRail.activate(:secondary) do - if self.md5.present? && (ns = self.infer_namespace) + if md5.present? && (ns = infer_namespace) scope = Attachment.where(md5: md5, namespace: ns, root_attachment_id: nil, content_type: content_type) scope = scope.where.not(filename: nil) scope = scope.where("id<>?", self) unless new_record? @@ -532,7 +532,7 @@ def find_or_initialize_thumbnail(file_name_suffix) # Stub for a #process_attachment method in a processor def process_attachment @saved_attachment = save_attachment? - run_before_attachment_saved if @saved_attachment && self.respond_to?(:run_before_attachment_saved) + run_before_attachment_saved if @saved_attachment && respond_to?(:run_before_attachment_saved) @saved_attachment end @@ -563,7 +563,7 @@ def after_process_attachment save_to_storage @temp_paths.clear @saved_attachment = nil - run_after_attachment_saved if self.respond_to?(:run_after_attachment_saved) + run_after_attachment_saved if respond_to?(:run_after_attachment_saved) run_callbacks(:save_and_attachment_processing) end @@ -588,7 +588,7 @@ def resize_image_or_thumbnail!(img) # Removes the thumbnails for the attachment, if it has any def destroy_thumbnails - self.thumbnails.each(&:destroy) if thumbnailable? + thumbnails.each(&:destroy) if thumbnailable? end end end diff --git a/gems/attachment_fu/lib/attachment_fu/backends/file_system_backend.rb b/gems/attachment_fu/lib/attachment_fu/backends/file_system_backend.rb index 9a44c5f2804a2..5805a9e82123e 100644 --- a/gems/attachment_fu/lib/attachment_fu/backends/file_system_backend.rb +++ b/gems/attachment_fu/lib/attachment_fu/backends/file_system_backend.rb @@ -81,8 +81,8 @@ def filename=(value) end def sanitize_filename(filename) - if self.respond_to?(:root_attachment) && self.root_attachment && self.root_attachment.filename - filename = self.root_attachment.filename + if respond_to?(:root_attachment) && root_attachment && root_attachment.filename + filename = root_attachment.filename else filename = Attachment.truncate_filename(filename, 255) filename.gsub!(%r{/| }, '_') diff --git a/gems/attachment_fu/lib/attachment_fu/backends/s3_backend.rb b/gems/attachment_fu/lib/attachment_fu/backends/s3_backend.rb index 9cd8fa79cf8b4..d3309201f325d 100644 --- a/gems/attachment_fu/lib/attachment_fu/backends/s3_backend.rb +++ b/gems/attachment_fu/lib/attachment_fu/backends/s3_backend.rb @@ -166,8 +166,8 @@ def filename=(value) end def sanitize_filename(filename) - if self.respond_to?(:root_attachment) && self.root_attachment && self.root_attachment.filename - self.root_attachment.filename + if respond_to?(:root_attachment) && root_attachment && root_attachment.filename + root_attachment.filename else Attachment.truncate_filename(filename, 255) do |component, len| CanvasTextHelper.cgi_escape_truncate(component, len) @@ -182,7 +182,7 @@ def attachment_path_id # INSTRUCTURE: fallback to old path style if there is no cluster attribute def namespaced_path - obj = (respond_to?(:root_attachment) && self.root_attachment) || self + obj = (respond_to?(:root_attachment) && root_attachment) || self if (namespace = obj.read_attribute(:namespace)) File.join(namespace, obj.attachment_options[:path_prefix]) else diff --git a/gems/bookmarked_collection/lib/bookmarked_collection/simple_bookmarker.rb b/gems/bookmarked_collection/lib/bookmarked_collection/simple_bookmarker.rb index 56f4c2722dcd7..e8d89e1fd7471 100644 --- a/gems/bookmarked_collection/lib/bookmarked_collection/simple_bookmarker.rb +++ b/gems/bookmarked_collection/lib/bookmarked_collection/simple_bookmarker.rb @@ -55,7 +55,7 @@ module BookmarkedCollection class Bookmark < Array def <=>(other) - length = [self.size, other.size].min + length = [size, other.size].min length.times do |i| if self[i].nil? && other[i].nil? next diff --git a/gems/broadcast_policy/lib/broadcast_policy/instance_methods.rb b/gems/broadcast_policy/lib/broadcast_policy/instance_methods.rb index 713a64453a011..56ffb9e0b9aa1 100644 --- a/gems/broadcast_policy/lib/broadcast_policy/instance_methods.rb +++ b/gems/broadcast_policy/lib/broadcast_policy/instance_methods.rb @@ -99,14 +99,14 @@ def broadcast_notifications(prior_version = nil) def save_without_broadcasting @skip_broadcasts = true - self.save + save ensure @skip_broadcasts = false end def save_without_broadcasting! @skip_broadcasts = true - self.save! + save! ensure @skip_broadcasts = false end diff --git a/gems/broadcast_policy/lib/broadcast_policy/notification_policy.rb b/gems/broadcast_policy/lib/broadcast_policy/notification_policy.rb index dbb8f54ed2714..64af21e1bad5a 100644 --- a/gems/broadcast_policy/lib/broadcast_policy/notification_policy.rb +++ b/gems/broadcast_policy/lib/broadcast_policy/notification_policy.rb @@ -36,13 +36,13 @@ def initialize(dispatch) # reasons. def broadcast(record) return if record.respond_to?(:skip_broadcasts) && record.skip_broadcasts - return unless record.instance_eval(&self.whenever) + return unless record.instance_eval(&whenever) - notification = BroadcastPolicy.notification_finder.by_name(self.dispatch) + notification = BroadcastPolicy.notification_finder.by_name(dispatch) return if notification.nil? record.class.connection.after_transaction_commit do - to_list = record.instance_eval(&self.to) + to_list = record.instance_eval(&to) to_list = Array(to_list).flatten next if to_list.empty? @@ -50,7 +50,7 @@ def broadcast(record) to_list.each_slice(NotificationPolicy.slice_size) do |to_slice| BroadcastPolicy.notifier.send_notification( record, - self.dispatch, + dispatch, notification, to_slice, data diff --git a/gems/broadcast_policy/lib/broadcast_policy/policy_list.rb b/gems/broadcast_policy/lib/broadcast_policy/policy_list.rb index 1717bd7ee9b57..3140fe9b4dc01 100644 --- a/gems/broadcast_policy/lib/broadcast_policy/policy_list.rb +++ b/gems/broadcast_policy/lib/broadcast_policy/policy_list.rb @@ -26,7 +26,7 @@ def initialize end def populate(&block) - self.instance_eval(&block) + instance_eval(&block) @current_notification = nil end @@ -51,22 +51,22 @@ def current_notification protected :current_notification def to(&block) - self.current_notification.to = block + current_notification.to = block end def whenever(&block) - self.current_notification.whenever = block + current_notification.whenever = block end def data(&block) - self.current_notification.data = block + current_notification.data = block end # filter_asset_by_recipient is a way for the asset (ie assignment, announcement) # to filter users out that do not apply to the notification like when a due # date is different for a specific user when using variable due dates. def filter_asset_by_recipient(&block) - self.current_notification.recipient_filter = block + current_notification.recipient_filter = block end def find_policy_for(notification) diff --git a/gems/canvas_cache/lib/canvas_cache/redis.rb b/gems/canvas_cache/lib/canvas_cache/redis.rb index b7f9d67d2683e..a548eec8dcf2d 100644 --- a/gems/canvas_cache/lib/canvas_cache/redis.rb +++ b/gems/canvas_cache/lib/canvas_cache/redis.rb @@ -50,7 +50,7 @@ def self.config end def self.enabled? - @enabled ||= self.config.present? + @enabled ||= config.present? end def self.disconnect! @@ -172,7 +172,7 @@ def self.handle_redis_failure(failure_retval, redis_name) Rails.logger.error "Failure handling redis command on #{redis_name}: #{e.inspect}" settings_store.skip_cache do - if self.ignore_redis_failures? + if ignore_redis_failures? CanvasCache.invoke_on_captured_error(e) last_redis_failure[redis_name] = Time.zone.now failure_retval @@ -230,7 +230,7 @@ def process(commands, *a, &b) if last_command == 'set' && (last_command_args.include?('XX') || last_command_args.include?('NX')) failure_val = :failure end - CanvasCache::Redis.handle_redis_failure(failure_val, self.location) do + CanvasCache::Redis.handle_redis_failure(failure_val, location) do super end end diff --git a/gems/canvas_errors/lib/canvas_errors.rb b/gems/canvas_errors/lib/canvas_errors.rb index 99b37826d78c3..8b0e53d4f883c 100644 --- a/gems/canvas_errors/lib/canvas_errors.rb +++ b/gems/canvas_errors/lib/canvas_errors.rb @@ -83,7 +83,7 @@ def self.capture(exception, data = {}, level = :error) # convenience method, use this if you want to apply the 'type' tag without # having to pass in a whole hash def self.capture_exception(type, exception, level = :error) - self.capture(exception, { tags: { type: type.to_s } }, level) + capture(exception, { tags: { type: type.to_s } }, level) end # This is really just for clearing out the registry during tests, diff --git a/gems/canvas_ext/lib/canvas_ext/array.rb b/gems/canvas_ext/lib/canvas_ext/array.rb index 02fbd19da325b..c91243fd3e44f 100644 --- a/gems/canvas_ext/lib/canvas_ext/array.rb +++ b/gems/canvas_ext/lib/canvas_ext/array.rb @@ -23,8 +23,8 @@ def cache_key if @cache_key @cache_key else - value = self.collect { |element| ActiveSupport::Cache.expand_cache_key(element) }.to_param - @cache_key = value unless self.frozen? + value = collect { |element| ActiveSupport::Cache.expand_cache_key(element) }.to_param + @cache_key = value unless frozen? value end end diff --git a/gems/canvas_http/lib/canvas_http.rb b/gems/canvas_http/lib/canvas_http.rb index 98f1e8e02ed19..b4d2479b738e8 100644 --- a/gems/canvas_http/lib/canvas_http.rb +++ b/gems/canvas_http/lib/canvas_http.rb @@ -200,13 +200,13 @@ def self.validate_url(value, host: nil, scheme: nil, allowed_schemes: %w[http ht end raise ArgumentError if !allowed_schemes.nil? && !allowed_schemes.include?(uri.scheme.downcase) raise(RelativeUriError) if uri.host.nil? || uri.host.strip.empty? - raise InsecureUriError if check_host && self.insecure_host?(uri.host) + raise InsecureUriError if check_host && insecure_host?(uri.host) [value, uri] end def self.insecure_host?(host) - return unless (filters = self.blocked_ip_filters) + return unless (filters = blocked_ip_filters) resolved_addrs = Resolv.getaddresses(host) unless resolved_addrs.any? diff --git a/gems/canvas_panda_pub/lib/canvas_panda_pub/async_worker.rb b/gems/canvas_panda_pub/lib/canvas_panda_pub/async_worker.rb index 27ebb60780d6f..3acb1d38a0e7e 100644 --- a/gems/canvas_panda_pub/lib/canvas_panda_pub/async_worker.rb +++ b/gems/canvas_panda_pub/lib/canvas_panda_pub/async_worker.rb @@ -31,7 +31,7 @@ def initialize(start_thread = true) @logger = CanvasPandaPub.logger @interval = CanvasPandaPub.process_interval - self.start! if start_thread + start! if start_thread end def push(tag, p) @@ -53,7 +53,7 @@ def stop! end def start! - @thread = Thread.new { self.run_thread } + @thread = Thread.new { run_thread } end def run_thread diff --git a/gems/canvas_partman/lib/canvas_partman/concerns/partitioned.rb b/gems/canvas_partman/lib/canvas_partman/concerns/partitioned.rb index f1bf094f92baa..96d83dcae072c 100644 --- a/gems/canvas_partman/lib/canvas_partman/concerns/partitioned.rb +++ b/gems/canvas_partman/lib/canvas_partman/concerns/partitioned.rb @@ -148,7 +148,7 @@ def arel_table_from_key_values(attributes) @arel_tables ||= {} @arel_tables[partition_table_name] ||= if ::ActiveRecord.version < Gem::Version.new('5') - Arel::Table.new(partition_table_name, { engine: self.arel_engine }) + Arel::Table.new(partition_table_name, { engine: arel_engine }) else Arel::Table.new(partition_table_name, type_caster: type_caster) end diff --git a/gems/canvas_partman/lib/canvas_partman/partition_manager.rb b/gems/canvas_partman/lib/canvas_partman/partition_manager.rb index d8621dfebf05f..4a0854556932b 100644 --- a/gems/canvas_partman/lib/canvas_partman/partition_manager.rb +++ b/gems/canvas_partman/lib/canvas_partman/partition_manager.rb @@ -141,7 +141,7 @@ def drop_partition_table(table_name) end def initialize(base_class) - raise NotImplementedError if self.instance_of?(PartitionManager) + raise NotImplementedError if instance_of?(PartitionManager) @base_class = base_class end diff --git a/gems/canvas_partman/lib/canvas_partman/partition_manager/by_id.rb b/gems/canvas_partman/lib/canvas_partman/partition_manager/by_id.rb index b4c5c3275b56c..963b3265c44b9 100644 --- a/gems/canvas_partman/lib/canvas_partman/partition_manager/by_id.rb +++ b/gems/canvas_partman/lib/canvas_partman/partition_manager/by_id.rb @@ -69,7 +69,7 @@ def ensure_or_check_partitions(advance, create_partitions) partitions.last[base_class.table_name.length + 1..].to_i end - if self.partition_on_primary_key? + if partition_on_primary_key? partitions.reverse_each do |partition| break if empties >= advance break if base_class.from(base_class.connection.quote_table_name(partition)).exists? @@ -77,7 +77,7 @@ def ensure_or_check_partitions(advance, create_partitions) empties += 1 end else - id = self.maximum_foreign_id + id = maximum_foreign_id last_needed = id ? (id / base_class.partition_size) : -1 # yes `empties` could be negative but that just means we'll make even more partitions to catch up empties = current - last_needed diff --git a/gems/canvas_partman/spec/fixtures/animal.rb b/gems/canvas_partman/spec/fixtures/animal.rb index e54c1bd1b61da..956af67842294 100644 --- a/gems/canvas_partman/spec/fixtures/animal.rb +++ b/gems/canvas_partman/spec/fixtures/animal.rb @@ -25,7 +25,7 @@ class CanvasPartmanTest::Animal < ActiveRecord::Base belongs_to :zoo, class_name: 'CanvasPartmanTest::Zoo' def self.create_schema - self.drop_schema + drop_schema CanvasPartmanTest::SchemaHelper.create_table :partman_animals do |t| t.string :race diff --git a/gems/canvas_partman/spec/fixtures/trail.rb b/gems/canvas_partman/spec/fixtures/trail.rb index 9148ca18faca8..8c1ecc6f98cd5 100644 --- a/gems/canvas_partman/spec/fixtures/trail.rb +++ b/gems/canvas_partman/spec/fixtures/trail.rb @@ -28,7 +28,7 @@ class CanvasPartmanTest::Trail < ActiveRecord::Base belongs_to :zoo, class_name: 'CanvasPartmanTest::Zoo' def self.create_schema - self.drop_schema + drop_schema CanvasPartmanTest::SchemaHelper.create_table :partman_trails do |t| t.string :name diff --git a/gems/canvas_partman/spec/fixtures/week_event.rb b/gems/canvas_partman/spec/fixtures/week_event.rb index c8478f88daa20..5e352d6729a85 100644 --- a/gems/canvas_partman/spec/fixtures/week_event.rb +++ b/gems/canvas_partman/spec/fixtures/week_event.rb @@ -25,14 +25,14 @@ class CanvasPartmanTest::WeekEvent < ActiveRecord::Base self.table_name = 'partman_week_events' def self.create_schema - self.drop_schema + drop_schema - CanvasPartmanTest::SchemaHelper.create_table(self.table_name.to_sym) do |t| + CanvasPartmanTest::SchemaHelper.create_table(table_name.to_sym) do |t| t.datetime :created_at end end def self.drop_schema - CanvasPartmanTest::SchemaHelper.drop_table(self.table_name.to_sym, cascade: true) + CanvasPartmanTest::SchemaHelper.drop_table(table_name.to_sym, cascade: true) end end diff --git a/gems/canvas_partman/spec/fixtures/zoo.rb b/gems/canvas_partman/spec/fixtures/zoo.rb index 13d3bb1b7451c..f82d4bb9d73f3 100644 --- a/gems/canvas_partman/spec/fixtures/zoo.rb +++ b/gems/canvas_partman/spec/fixtures/zoo.rb @@ -29,7 +29,7 @@ class CanvasPartmanTest::Zoo < ActiveRecord::Base dependent: :destroy def self.create_schema - self.drop_schema + drop_schema SchemaHelper.create_table :partman_zoos do |t| t.timestamps null: false diff --git a/gems/canvas_partman/spec/support/schema_helper.rb b/gems/canvas_partman/spec/support/schema_helper.rb index a831be49bb3e2..689b5f901b6e3 100644 --- a/gems/canvas_partman/spec/support/schema_helper.rb +++ b/gems/canvas_partman/spec/support/schema_helper.rb @@ -28,7 +28,7 @@ def table_exists?(table_name) end def drop_table(table_name, opts = {}) - if self.table_exists?(table_name) + if table_exists?(table_name) # `drop_table` doesn't really accept any options, so cascade must be # done manually. # diff --git a/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base.rb b/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base.rb index aeb764cfe6b67..3769edad6f840 100644 --- a/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base.rb +++ b/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base.rb @@ -48,7 +48,7 @@ def run(responses) end def self.question_type - (self.name.demodulize.underscore + '_question').to_sym + (name.demodulize.underscore + '_question').to_sym end private diff --git a/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base/dsl.rb b/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base/dsl.rb index 8b3babe003914..b8643558aaa98 100644 --- a/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base/dsl.rb +++ b/gems/canvas_quiz_statistics/lib/canvas_quiz_statistics/analyzers/base/dsl.rb @@ -58,7 +58,7 @@ def metric(key, &calculator) deps, key = key.values.flatten, key.keys.first end - self.metrics[question_type] << { + metrics[question_type] << { key: key.to_sym, context: deps, calculator: calculator @@ -78,7 +78,7 @@ def metric(key, &calculator) # end # def inherit_metrics(question_type) - self.metrics[self.question_type] += self.metrics_for(question_type).clone + metrics[self.question_type] += metrics_for(question_type).clone end # Inherit one or more metrics from another question type. @@ -99,7 +99,7 @@ def inherit_metrics(question_type) # end # def inherit(*metric_keys, options) - metrics = self.metrics_for(options[:from]) + metrics = metrics_for(options[:from]) return inherit_metrics(options[:from]) if metric_keys.first == :all @@ -110,7 +110,7 @@ def inherit(*metric_keys, options) raise "Metric #{metric_key} could not be found in #{options[:from]}" end - self.metrics[self.question_type] << metric + self.metrics[question_type] << metric end end @@ -124,6 +124,6 @@ def metrics_for(question_type) target = question_type.to_s target = "#{target}_question" unless /_question$/.match?(target) - self.metrics[target.to_sym] + metrics[target.to_sym] end end diff --git a/gems/canvas_sanitize/lib/canvas_sanitize/canvas_sanitize.rb b/gems/canvas_sanitize/lib/canvas_sanitize/canvas_sanitize.rb index 8e81f34d1189f..a3571fc2baaab 100644 --- a/gems/canvas_sanitize/lib/canvas_sanitize/canvas_sanitize.rb +++ b/gems/canvas_sanitize/lib/canvas_sanitize/canvas_sanitize.rb @@ -384,17 +384,17 @@ module InstanceMethods def fully_sanitize_fields fields_hash = self.class.fully_sanitize_fields_config || {} fields_hash.each do |field, config| - next unless self.attribute_changed?(field) + next unless attribute_changed?(field) config ||= Sanitize::Config::RESTRICTED config = Sanitize::Config::RESTRICTED if config.empty? # Doesn't try to sanitize nil - f = self.send(field) + f = send(field) next unless f next unless f.is_a?(String) || f.is_a?(IO) val = Sanitize.clean(f, config) - self.send((field.to_s + "="), val) + send((field.to_s + "="), val) end end end # InstanceMethods diff --git a/gems/canvas_security/lib/canvas_security.rb b/gems/canvas_security/lib/canvas_security.rb index 3ac39a552f5d7..df256dbc52745 100644 --- a/gems/canvas_security/lib/canvas_security.rb +++ b/gems/canvas_security/lib/canvas_security.rb @@ -93,7 +93,7 @@ def self.config def self.encrypt_data(data) nonce = SecureRandom.bytes(12) encryptor = OpenSSL::Cipher.new('aes-256-gcm').encrypt - encryptor.key = Digest::SHA1.hexdigest(self.encryption_key)[0...32] + encryptor.key = Digest::SHA1.hexdigest(encryption_key)[0...32] encryptor.iv = nonce encryptor.auth_data = 'Canvas-v1.0.0' encrypted_data = encryptor.update(data) + encryptor.final @@ -103,7 +103,7 @@ def self.encrypt_data(data) def self.decrypt_data(data, nonce, tag) decipher = OpenSSL::Cipher.new('aes-256-gcm').decrypt - decipher.key = Digest::SHA1.hexdigest(self.encryption_key)[0...32] + decipher.key = Digest::SHA1.hexdigest(encryption_key)[0...32] decipher.iv = nonce decipher.auth_tag = tag decipher.auth_data = 'Canvas-v1.0.0' diff --git a/gems/canvas_stringex/lib/lucky_sneaks/acts_as_url.rb b/gems/canvas_stringex/lib/lucky_sneaks/acts_as_url.rb index 28c7d980a3cfa..718afe1719b5a 100644 --- a/gems/canvas_stringex/lib/lucky_sneaks/acts_as_url.rb +++ b/gems/canvas_stringex/lib/lucky_sneaks/acts_as_url.rb @@ -51,7 +51,7 @@ def acts_as_url(attribute, options = {}) cattr_reader :only_when_blank attr_writer :only_when_blank - self.class_eval do + class_eval do def only_when_blank return @only_when_blank unless @only_when_blank.nil? # can override only_when_blank temporarily @@ -79,7 +79,7 @@ def only_when_blank # on a large selection, you will get much better results writing your own version with # using pagination. def initialize_urls - where(self.url_attribute => nil).each do |instance| + where(url_attribute => nil).each do |instance| instance.send :ensure_unique_url instance.save end @@ -90,8 +90,8 @@ def initialize_urls def ensure_unique_url url_attribute = self.class.url_attribute - base_url = self.send(url_attribute) - base_url = self.send(self.class.attribute_to_urlify).to_s.to_url if base_url.blank? || !self.only_when_blank + base_url = send(url_attribute) + base_url = send(self.class.attribute_to_urlify).to_s.to_url if base_url.blank? || !only_when_blank conditions = [+"#{url_attribute} LIKE ?", base_url + '%'] unless new_record? conditions.first << " and id != ?" diff --git a/gems/canvas_stringex/lib/lucky_sneaks/string_extensions.rb b/gems/canvas_stringex/lib/lucky_sneaks/string_extensions.rb index c7d40cef0416d..5419d353d96b3 100644 --- a/gems/canvas_stringex/lib/lucky_sneaks/string_extensions.rb +++ b/gems/canvas_stringex/lib/lucky_sneaks/string_extensions.rb @@ -35,7 +35,7 @@ def to_html(lite_mode = false) if defined?(RedCloth) if lite_mode RedCloth.new(self, [:lite_mode]).to_html - elsif self.include?('
')
+        elsif include?('
')
           RedCloth.new(self).to_html.tr("\t", "")
         else
           RedCloth.new(self).to_html.tr("\t", "").gsub(/\n\n/, "")
diff --git a/gems/canvas_time/lib/canvas_time.rb b/gems/canvas_time/lib/canvas_time.rb
index 7e6287b2a8783..3df002bc4db78 100644
--- a/gems/canvas_time/lib/canvas_time.rb
+++ b/gems/canvas_time/lib/canvas_time.rb
@@ -49,7 +49,7 @@ def self.try_parse(maybe_time, default = nil)
   end
 
   def utc_datetime
-    timestamp = self.getutc
+    timestamp = getutc
     DateTime.civil(timestamp.year,
                    timestamp.month,
                    timestamp.day,
diff --git a/gems/canvas_unzip/lib/canvas_unzip.rb b/gems/canvas_unzip/lib/canvas_unzip.rb
index 89b90e3c5c0da..ef6780ca90177 100644
--- a/gems/canvas_unzip/lib/canvas_unzip.rb
+++ b/gems/canvas_unzip/lib/canvas_unzip.rb
@@ -207,9 +207,9 @@ def size
 
     # yields byte count
     def extract(dest_path, overwrite = false, maximum_size = DEFAULT_BYTE_LIMIT)
-      dir = self.directory? ? dest_path : File.dirname(dest_path)
+      dir = directory? ? dest_path : File.dirname(dest_path)
       FileUtils.mkdir_p(dir) unless File.exist?(dir)
-      return unless self.file?
+      return unless file?
 
       raise SizeLimitExceeded if size > maximum_size
       if File.exist?(dest_path) && !overwrite
diff --git a/gems/diigo/lib/diigo/connection.rb b/gems/diigo/lib/diigo/connection.rb
index ebf0286d1fcb1..85f621d664e44 100644
--- a/gems/diigo/lib/diigo/connection.rb
+++ b/gems/diigo/lib/diigo/connection.rb
@@ -72,7 +72,7 @@ def self.diigo_post_bookmark(service, url, title, desc, tags)
     end
 
     def self.key
-      self.config['api_key']
+      config['api_key']
     end
 
     def self.config_check(settings)
diff --git a/gems/event_stream/lib/event_stream/index.rb b/gems/event_stream/lib/event_stream/index.rb
index b020116971dc9..9041728ffde05 100644
--- a/gems/event_stream/lib/event_stream/index.rb
+++ b/gems/event_stream/lib/event_stream/index.rb
@@ -43,12 +43,12 @@ def initialize(event_stream, &blk)
   end
 
   def find_with(args, options)
-    strategy = self.strategy_for(options[:strategy])
+    strategy = strategy_for(options[:strategy])
     strategy.find_with(args, options)
   end
 
   def find_ids_with(args, options)
-    strategy = self.strategy_for(options[:strategy])
+    strategy = strategy_for(options[:strategy])
     strategy.find_ids_with(args, options)
   end
 
diff --git a/gems/event_stream/spec/event_stream/index_strategy/active_record_spec.rb b/gems/event_stream/spec/event_stream/index_strategy/active_record_spec.rb
index ec93a06c13f41..942c451964e5f 100644
--- a/gems/event_stream/spec/event_stream/index_strategy/active_record_spec.rb
+++ b/gems/event_stream/spec/event_stream/index_strategy/active_record_spec.rb
@@ -32,7 +32,7 @@ def self.paginate(**)
       end
 
       def self.to_ary
-        [self.new]
+        [new]
       end
 
       def self.next_page
@@ -67,9 +67,9 @@ def self.applied_conditions
                       :active_record_type => fake_record_type)
       ar_cls = fake_record_type
       base_index = EventStream::Index.new(stream) do
-        self.table "table"
-        self.entry_proc lambda { |_a1, _a2| }
-        self.ar_scope_proc lambda { |a1, a2| ar_cls.where({ one: a1.id, two: a2.id }) }
+        table "table"
+        entry_proc lambda { |_a1, _a2| }
+        ar_scope_proc lambda { |a1, a2| ar_cls.where({ one: a1.id, two: a2.id }) }
       end
       @index = base_index.strategy_for(:active_record)
     end
diff --git a/gems/event_stream/spec/event_stream/index_strategy/cassandra_spec.rb b/gems/event_stream/spec/event_stream/index_strategy/cassandra_spec.rb
index 9c09e4f5e441f..208918bb0b1f9 100644
--- a/gems/event_stream/spec/event_stream/index_strategy/cassandra_spec.rb
+++ b/gems/event_stream/spec/event_stream/index_strategy/cassandra_spec.rb
@@ -420,7 +420,7 @@ def setup_fetch(start, requested)
       @table = double('table')
       table = @table
       @stream = EventStream::Stream.new do
-        self.database database
+        database database
         self.table table
       end
       base_index = @stream.add_index :thing do
diff --git a/gems/event_stream/spec/event_stream/stream_spec.rb b/gems/event_stream/spec/event_stream/stream_spec.rb
index 780dcf5108900..63f074c3ca93c 100644
--- a/gems/event_stream/spec/event_stream/stream_spec.rb
+++ b/gems/event_stream/spec/event_stream/stream_spec.rb
@@ -60,7 +60,7 @@ def database.keyspace
         self.table table
         self.id_column id_column
         self.record_type record_type
-        self.read_consistency_level 'ALL'
+        read_consistency_level 'ALL'
       end
 
       expect(stream.database).to eq database
@@ -120,7 +120,7 @@ def database.keyspace
         self.table table
         self.id_column id_column
         self.record_type record_type
-        self.read_consistency_level 'ALL'
+        read_consistency_level 'ALL'
       end
 
       expect(stream.database).to be database
@@ -139,7 +139,7 @@ def database.keyspace
         self.table table
         self.id_column id_column
         self.record_type record_type
-        self.read_consistency_level 'ALL'
+        read_consistency_level 'ALL'
       end
 
       expect(stream.database).to be database
@@ -157,7 +157,7 @@ def database.keyspace
         self.table table
         self.id_column id_column
         self.record_type record_type
-        self.read_consistency_level 'ALL'
+        read_consistency_level 'ALL'
       end
 
       expect(stream.database).to be nil
@@ -187,13 +187,13 @@ def self.name
       end
 
       stream = EventStream::Stream.new do
-        self.backend_strategy -> { :active_record }
+        backend_strategy -> { :active_record }
         self.database -> {}
         self.table table
         self.id_column id_column
         self.record_type record_type
-        self.read_consistency_level 'ALL'
-        self.active_record_type ar_type
+        read_consistency_level 'ALL'
+        active_record_type ar_type
       end
 
       expect(stream.database_name).to eq("active_record_db")
@@ -243,7 +243,7 @@ def self.name
       it "changes at runtime with different setting" do
         strat_value = :cassandra
         stream = EventStream::Stream.new do
-          self.backend_strategy -> { strat_value }
+          backend_strategy -> { strat_value }
           self.table "table"
         end
         expect(stream.current_backend.class).to eq(EventStream::Backend::Cassandra)
@@ -436,7 +436,7 @@ def self.name
         table = @table
         @index = @stream.add_index :thing do
           self.table table
-          self.entry_proc lambda { |record| record.entry }
+          entry_proc lambda { |record| record.entry }
         end
         @index_strategy = @index.strategy_for(:cassandra)
 
diff --git a/gems/incoming_mail_processor/lib/incoming_mail_processor/incoming_message_processor.rb b/gems/incoming_mail_processor/lib/incoming_mail_processor/incoming_message_processor.rb
index 70d209a64f635..22f8dcf391ed3 100644
--- a/gems/incoming_mail_processor/lib/incoming_mail_processor/incoming_message_processor.rb
+++ b/gems/incoming_mail_processor/lib/incoming_mail_processor/incoming_message_processor.rb
@@ -114,10 +114,10 @@ def configure_settings(config)
 
         config.symbolize_keys.each do |key, value|
           if IncomingMailProcessor::Settings.members.map(&:to_sym).include?(key)
-            self.settings.send("#{key}=", value)
+            settings.send("#{key}=", value)
           elsif IncomingMailProcessor::DeprecatedSettings.members.map(&:to_sym).include?(key)
             logger&.warn("deprecated setting sent to IncomingMessageProcessor: #{key}")
-            self.deprecated_settings.send("#{key}=", value)
+            deprecated_settings.send("#{key}=", value)
           else
             raise "unrecognized setting sent to IncomingMessageProcessor: #{key}"
           end
@@ -162,12 +162,12 @@ def initialize(message_handler, error_reporter)
     end
 
     def self.queue_processors
-      if self.run_periodically?
-        imp = self.new(IncomingMail::MessageHandler.new, ErrorReport::Reporter.new)
-        self.workers.times do |worker_id|
-          if self.dedicated_workers_per_mailbox
+      if run_periodically?
+        imp = new(IncomingMail::MessageHandler.new, ErrorReport::Reporter.new)
+        workers.times do |worker_id|
+          if dedicated_workers_per_mailbox
             # Launch one per mailbox
-            self.mailbox_accounts.each do |account|
+            mailbox_accounts.each do |account|
               imp.delay(singleton: "IncomingMailProcessor::IncomingMessageProcessor#process:#{worker_id}:#{account.address}")
                  .process({ worker_id: worker_id, mailbox_account_address: account.address })
             end
diff --git a/gems/json_token/lib/json_token.rb b/gems/json_token/lib/json_token.rb
index dc172c0acb7a3..ae99da3fd231c 100644
--- a/gems/json_token/lib/json_token.rb
+++ b/gems/json_token/lib/json_token.rb
@@ -25,7 +25,7 @@
 # encoded JSON, e.g. to use in a URL
 module JSONToken
   def self.encode(data)
-    data = self.walk_json(data, self.method(:encode_binary_string))
+    data = walk_json(data, method(:encode_binary_string))
     Base64.encode64(data.to_json).tr('+/', '-_').gsub(/=|\n/, '')
   end
 
@@ -37,7 +37,7 @@ def self.decode(token)
     json = JSON.parse("[#{json}]")
     raise JSON::ParserError unless json.size == 1
 
-    self.walk_json(json.first, self.method(:decode_binary_string))
+    walk_json(json.first, method(:decode_binary_string))
   end
 
   def self.walk_json(value, method)
diff --git a/gems/live_events/lib/live_events/async_worker.rb b/gems/live_events/lib/live_events/async_worker.rb
index bdbd7b51d38b1..22074dcc98652 100644
--- a/gems/live_events/lib/live_events/async_worker.rb
+++ b/gems/live_events/lib/live_events/async_worker.rb
@@ -35,7 +35,7 @@ def initialize(start_thread = true, stream_client:, stream_name:)
       @stream_client = stream_client
       @stream_name = stream_name
 
-      self.start! if start_thread
+      start! if start_thread
     end
 
     def push(event, partition_key = SecureRandom.uuid)
@@ -76,7 +76,7 @@ def stop!
     def start!
       return if @running
 
-      @thread = Thread.new { self.run_thread }
+      @thread = Thread.new { run_thread }
       @running = true
       at_exit { stop! unless stopped? }
     end
diff --git a/gems/lti-advantage/lib/lti_advantage/messages/jwt_message.rb b/gems/lti-advantage/lib/lti_advantage/messages/jwt_message.rb
index 31de2354b563d..8de0a34facee1 100644
--- a/gems/lti-advantage/lib/lti_advantage/messages/jwt_message.rb
+++ b/gems/lti-advantage/lib/lti_advantage/messages/jwt_message.rb
@@ -115,7 +115,7 @@ def lti1p1
     end
 
     def read_attribute(attribute)
-      self.send(attribute)
+      send(attribute)
     end
 
     def to_h
@@ -123,7 +123,7 @@ def to_h
     end
 
     def to_jws(private_key, alg = :RS256)
-      self.class.create_jws(self.to_h, private_key, alg)
+      self.class.create_jws(to_h, private_key, alg)
     end
   end
 end
diff --git a/gems/lti_outbound/lib/lti_outbound/lti_model.rb b/gems/lti_outbound/lib/lti_outbound/lti_model.rb
index 004cf9c690ecd..c7135881ea562 100644
--- a/gems/lti_outbound/lib/lti_outbound/lti_model.rb
+++ b/gems/lti_outbound/lib/lti_outbound/lti_model.rb
@@ -32,10 +32,10 @@ def proc_writer(*methods)
         methods.each do |method|
           define_method(method) do
             variable_name = "@#{method}"
-            value = self.instance_variable_get(variable_name)
+            value = instance_variable_get(variable_name)
             if value.is_a?(Proc)
               value = value.call
-              self.instance_variable_set(variable_name, value)
+              instance_variable_set(variable_name, value)
             end
             return value
           end
diff --git a/gems/plugins/academic_benchmark/lib/academic_benchmark.rb b/gems/plugins/academic_benchmark/lib/academic_benchmark.rb
index c056569d9affd..f071557f0d423 100644
--- a/gems/plugins/academic_benchmark/lib/academic_benchmark.rb
+++ b/gems/plugins/academic_benchmark/lib/academic_benchmark.rb
@@ -53,11 +53,11 @@ def self.config
   end
 
   def self.check_config
-    if !self.config
+    if !config
       "(needs partner_key and partner_id)"
-    elsif self.config[:partner_key].blank?
+    elsif config[:partner_key].blank?
       "(needs partner_key)"
-    elsif self.config[:partner_id].blank?
+    elsif config[:partner_id].blank?
       "(needs partner_id)"
     end
   end
@@ -86,7 +86,7 @@ def self.nat_stds_guid_from_auths(authorities)
   # browsed in order to retrieve specifics like NGSS and Common Core
   ##
   def self.retrieve_authorities(api)
-    self.sort_authorities(api.standards.authorities)
+    sort_authorities(api.standards.authorities)
   end
 
   # sort national standards at the top, followed by country standards,
@@ -95,9 +95,9 @@ def self.sort_authorities(authorities)
     national_stds, rest = authorities.partition { |a| NATIONAL_STDS.include?(a.code) || NATIONAL_STDS.include?(a.description) }
     country_stds, rest = rest.partition { |a| COUNTRY_STDS.include?(a.description) }
     [
-      self.sort_authorities_by_description(national_stds),
-      self.sort_authorities_by_description(country_stds),
-      self.sort_authorities_by_description(rest)
+      sort_authorities_by_description(national_stds),
+      sort_authorities_by_description(country_stds),
+      sort_authorities_by_description(rest)
     ].flatten
   end
 
@@ -110,12 +110,12 @@ def self.sort_authorities_by_description(authorities)
   # These can be passed to the `create` action
   ##
   def self.list_of_available_guids
-    api = self.api_handle
-    auth_list = self.retrieve_authorities(api)
+    api = api_handle
+    auth_list = retrieve_authorities(api)
 
     # prepend the common core, next gen science standards (Achieve),
     # and the ISTE (NETS) standards to the list
-    auth_list.unshift(self.extract_nat_stds(api, self.nat_stds_guid_from_auths(auth_list)))
+    auth_list.unshift(extract_nat_stds(api, nat_stds_guid_from_auths(auth_list)))
     auth_list.unshift(api.standards.authority_publications(ACHIEVE_AUTHORITY))
     auth_list.unshift(api.standards.authority_publications(COMMON_CORE_AUTHORITY))
 
@@ -133,23 +133,23 @@ def self.list_of_available_guids
   class APIError < StandardError; end
 
   def self.import(guid, options = {})
-    is_auth = self.auth?(guid)
+    is_auth = auth?(guid)
     authority = is_auth ? guid : nil
     publication = is_auth ? nil : guid
     check_args(authority, publication)
-    self.ensure_ab_credentials
+    ensure_ab_credentials
 
     AcademicBenchmark.queue_migration_for(
       authority: authority,
       publication: publication,
-      user: self.authorized?,
+      user: authorized?,
       options: options
     ).first
   end
 
   def self.queue_migration_for(authority:, publication:, user:, options: {})
     cm = ContentMigration.new(context: Account.site_admin)
-    cm.converter_class = self.config['converter_class']
+    cm.converter_class = config['converter_class']
     cm.migration_settings[:migration_type] = 'academic_benchmark_importer'
     cm.migration_settings[:import_immediately] = true
     cm.migration_settings[:authority] = authority
@@ -172,7 +172,7 @@ def self.api_handle
   end
 
   def self.auth?(guid)
-    self.api_handle.standards.authorities.map(&:guid).include?(guid)
+    api_handle.standards.authorities.map(&:guid).include?(guid)
   end
 
   def self.check_args(authority, publication)
@@ -184,8 +184,8 @@ def self.check_args(authority, publication)
 
   def self.ensure_ab_credentials
     err = nil
-    err ||= self.ensure_partner_id
-    err ||= self.ensure_partner_key
+    err ||= ensure_partner_id
+    err ||= ensure_partner_key
     if err
       raise Canvas::Migration::Error,
             "Not importing academic benchmark data because the Academic Benchmarks #{err}"
@@ -205,8 +205,8 @@ def self.ensure_partner_key
   end
 
   def self.authorized?
-    self.check_for_import_rights(
-      user: self.ensure_real_user(user_id: self.ensure_user_id_set)
+    check_for_import_rights(
+      user: ensure_real_user(user_id: ensure_user_id_set)
     )
   end
 
diff --git a/gems/plugins/account_reports/lib/account_reports.rb b/gems/plugins/account_reports/lib/account_reports.rb
index 4c00531def18a..b7c3d987b0b8e 100644
--- a/gems/plugins/account_reports/lib/account_reports.rb
+++ b/gems/plugins/account_reports/lib/account_reports.rb
@@ -119,7 +119,7 @@ def self.generate_report(account_report)
                        else
                          " Unable to create error_report_id for #{e}"
                        end
-      self.finalize_report(account_report, error_message)
+      finalize_report(account_report, error_message)
       @er = nil
     end
   end
diff --git a/gems/plugins/account_reports/lib/account_reports/report_helper.rb b/gems/plugins/account_reports/lib/account_reports/report_helper.rb
index 1d2bea9dad976..9581b19b52b2a 100644
--- a/gems/plugins/account_reports/lib/account_reports/report_helper.rb
+++ b/gems/plugins/account_reports/lib/account_reports/report_helper.rb
@@ -425,7 +425,7 @@ def run_account_report_runner(report_runner, headers, files: nil)
       end
     rescue => e
       report_runner.fail
-      self.fail_with_error(e)
+      fail_with_error(e)
     ensure
       update_parallel_progress(account_report: @account_report, report_runner: report_runner)
       compile_parallel_report(headers, files: files) if last_account_report_runner?(@account_report)
@@ -537,7 +537,7 @@ class ExtendedCSV < CSVWithI18n
     def <<(row)
       if lineno % 1_000 == 0
         GuardRail.activate(:primary) do
-          report = self.instance_variable_get(:@account_report).reload
+          report = instance_variable_get(:@account_report).reload
           updates = {}
           updates[:current_line] = lineno
           updates[:progress] = (lineno.to_f / (report.total_lines + 1) * 100).to_i if report.total_lines
diff --git a/gems/plugins/account_reports/lib/account_reports/sis_exporter.rb b/gems/plugins/account_reports/lib/account_reports/sis_exporter.rb
index 8ac6b7dac0b57..f14dbfb5a4f8a 100644
--- a/gems/plugins/account_reports/lib/account_reports/sis_exporter.rb
+++ b/gems/plugins/account_reports/lib/account_reports/sis_exporter.rb
@@ -55,13 +55,13 @@ def csv
       when 0
         send_report
       when 1
-        csv = self.send(@reports.first)
+        csv = send(@reports.first)
         send_report(csv)
       else
         csvs = {}
 
         @reports.each do |report_name|
-          csvs[report_name] = self.send(report_name)
+          csvs[report_name] = send(report_name)
         end
         send_report(csvs)
         csvs
diff --git a/gems/plugins/qti_exporter/lib/qti/assessment_item_converter.rb b/gems/plugins/qti_exporter/lib/qti/assessment_item_converter.rb
index 9b13fbe6af4a5..27e5e2783811b 100644
--- a/gems/plugins/qti_exporter/lib/qti/assessment_item_converter.rb
+++ b/gems/plugins/qti_exporter/lib/qti/assessment_item_converter.rb
@@ -149,9 +149,9 @@ def create_instructure_question
           @question[:question_type] = @migration_type
           @question[:unsupported] = true
         elsif !%w[text_only_question file_upload_question].include?(@migration_type)
-          self.parse_question_data
+          parse_question_data
         else
-          self.get_feedback if @migration_type == 'file_upload_question'
+          get_feedback if @migration_type == 'file_upload_question'
           @question[:question_type] ||= @migration_type
         end
       rescue => e
diff --git a/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/middleware.rb b/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/middleware.rb
index 36070f5fcbf43..93d2bfaded7d8 100644
--- a/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/middleware.rb
+++ b/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/middleware.rb
@@ -58,9 +58,9 @@ def self.do_setup
         RespondusAPIPort::Methods.each do |definitions|
           opt = definitions.last
           if opt[:request_style] == :document
-            @router.add_document_operation(self.servant, *definitions)
+            @router.add_document_operation(servant, *definitions)
           else
-            @router.add_rpc_operation(self.servant, *definitions)
+            @router.add_rpc_operation(servant, *definitions)
           end
         end
         self.mapping_registry = UrnRespondusAPIMappingRegistry::EncodedRegistry
@@ -82,7 +82,7 @@ def call(env)
     end
 
     def handle(env)
-      self.servant.rack_env = env
+      servant.rack_env = env
       super(env)
     end
   end
diff --git a/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/urn_RespondusAPIServant.rb b/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/urn_RespondusAPIServant.rb
index 3e8523c6ce3e0..0ba0bc038b81e 100644
--- a/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/urn_RespondusAPIServant.rb
+++ b/gems/plugins/respondus_soap_endpoint/lib/respondus_soap_endpoint/urn_RespondusAPIServant.rb
@@ -81,11 +81,11 @@ def load_session(context)
                  end
 
       # verify that the session was created for this user
-      if self.user
+      if user
         if session['user_id']
-          raise(ActiveSupport::MessageVerifier::InvalidSignature) unless self.user.id == session['user_id']
+          raise(ActiveSupport::MessageVerifier::InvalidSignature) unless user.id == session['user_id']
         else
-          session['user_id'] = self.user.id
+          session['user_id'] = user.id
         end
       end
     end
diff --git a/gems/plugins/respondus_soap_endpoint/spec_canvas/integration/respondus_endpoint_spec.rb b/gems/plugins/respondus_soap_endpoint/spec_canvas/integration/respondus_endpoint_spec.rb
index a580aa9530930..a11fd49cb8b3e 100644
--- a/gems/plugins/respondus_soap_endpoint/spec_canvas/integration/respondus_endpoint_spec.rb
+++ b/gems/plugins/respondus_soap_endpoint/spec_canvas/integration/respondus_endpoint_spec.rb
@@ -248,7 +248,7 @@ def soap_request(method, userName, password, context, *args)
     mock_migration = ContentMigration.create!(context: @course)
     def mock_migration.export_content
       self.workflow_state = 'imported'
-      self.migration_settings[:imported_assets] = ["quizzes:quiz_xyz"]
+      migration_settings[:imported_assets] = ["quizzes:quiz_xyz"]
     end
     allow(ContentMigration).to receive(:new).and_return(mock_migration)
     allow(ContentMigration).to receive(:find).with(mock_migration.id).and_return(mock_migration)
diff --git a/gems/plugins/simply_versioned/lib/simply_versioned.rb b/gems/plugins/simply_versioned/lib/simply_versioned.rb
index 26ab18a49a497..a0c66cbe62d35 100644
--- a/gems/plugins/simply_versioned/lib/simply_versioned.rb
+++ b/gems/plugins/simply_versioned/lib/simply_versioned.rb
@@ -103,13 +103,13 @@ def simply_versioned(options = {})
 
       class_eval do
         def versioning_enabled=(enabled)
-          self.instance_variable_set(:@simply_versioned_enabled, enabled)
+          instance_variable_set(:@simply_versioned_enabled, enabled)
         end
 
         def versioning_enabled?
-          enabled = self.instance_variable_get(:@simply_versioned_enabled)
+          enabled = instance_variable_get(:@simply_versioned_enabled)
           if enabled.nil?
-            enabled = self.instance_variable_set(:@simply_versioned_enabled, self.simply_versioned_options[:automatic])
+            enabled = instance_variable_set(:@simply_versioned_enabled, simply_versioned_options[:automatic])
           end
           enabled
         end
@@ -135,21 +135,21 @@ def revert_to_version(version, options = {})
                 when Version
                   version
                 when Integer
-                  self.versions.where(number: version).first
+                  versions.where(number: version).first
                 end
 
       raise "Invalid version (#{version.inspect}) specified!" unless version
 
       options[:except] = options[:except].map(&:to_s)
 
-      self.update(YAML.load(version.yaml).except(*options[:except]))
+      update(YAML.load(version.yaml).except(*options[:except]))
     end
 
     # Invoke the supplied block passing the receiver as the sole block argument with
     # versioning enabled or disabled depending upon the value of the +enabled+ parameter
     # for the duration of the block.
     def with_versioning(enabled = true)
-      versioning_was_enabled = self.versioning_enabled?
+      versioning_was_enabled = versioning_enabled?
       explicit_versioning_was_enabled = @simply_versioned_explicit_enabled
       explicit_enabled = false
       if enabled.is_a?(Hash)
@@ -175,7 +175,7 @@ def without_versioning(&block)
     end
 
     def unversioned?
-      self.versions.nil? || !self.versions.exists?
+      versions.nil? || !versions.exists?
     end
 
     def versioned?
@@ -195,7 +195,7 @@ def version_number
       elsif @preloaded_current_version_number
         @preloaded_current_version_number
       else
-        self.versions.maximum(:number) || 0
+        versions.maximum(:number) || 0
       end
     end
 
@@ -220,27 +220,27 @@ def check_if_changes_are_worth_versioning
       @changes_are_worth_versioning = if simply_versioned_options[:when]
                                         simply_versioned_options[:when].call(self)
                                       else
-                                        (self.changes.keys.map(&:to_s) - simply_versioned_options[:exclude] - ["updated_at"]).present?
+                                        (changes.keys.map(&:to_s) - simply_versioned_options[:exclude] - ["updated_at"]).present?
                                       end
       true
     end
 
     def simply_versioned_create_version
-      if self.versioning_enabled?
+      if versioning_enabled?
         # INSTRUCTURE
         if @versioning_explicitly_enabled || @changes_are_worth_versioning
           @changes_are_worth_versioning = nil
           if simply_versioned_options[:explicit] && !@simply_versioned_explicit_enabled && versioned?
-            version = self.versions.current
-            version.yaml = self.attributes.except(*simply_versioned_options[:exclude]).to_yaml
+            version = versions.current
+            version.yaml = attributes.except(*simply_versioned_options[:exclude]).to_yaml
             if version.save
               simply_versioned_options[:on_update].try(:call, self, version)
             end
           else
-            version = self.versions.create(:yaml => self.attributes.except(*simply_versioned_options[:exclude]).to_yaml)
+            version = versions.create(:yaml => attributes.except(*simply_versioned_options[:exclude]).to_yaml)
             if version.valid?
               simply_versioned_options[:on_create].try(:call, self, version)
-              self.versions.clean_old_versions(simply_versioned_options[:keep].to_i) if simply_versioned_options[:keep]
+              versions.clean_old_versions(simply_versioned_options[:keep].to_i) if simply_versioned_options[:keep]
             end
           end
         end
@@ -300,7 +300,7 @@ def current_version
 
     # If the model instance has more versions than the limit specified, delete all excess older versions.
     def clean_old_versions(versions_to_keep)
-      where('number <= ?', self.maximum(:number) - versions_to_keep).each(&:destroy)
+      where('number <= ?', maximum(:number) - versions_to_keep).each(&:destroy)
     end
     alias_method :purge, :clean_old_versions
 
diff --git a/gems/plugins/simply_versioned/lib/simply_versioned/version.rb b/gems/plugins/simply_versioned/lib/simply_versioned/version.rb
index 3411bb36797b6..b075909b87d46 100644
--- a/gems/plugins/simply_versioned/lib/simply_versioned/version.rb
+++ b/gems/plugins/simply_versioned/lib/simply_versioned/version.rb
@@ -47,7 +47,7 @@ class Version < ActiveRecord::Base # :nodoc:
     def model
       @model ||= begin
         obj = versionable_type.constantize.new
-        YAML.load(self.yaml).each do |var_name, var_value|
+        YAML.load(yaml).each do |var_name, var_value|
           # INSTRUCTURE:  added if... so that if a column is removed in a migration after this was versioned it doesen't die with NoMethodError: undefined method `some_column_name=' for ...
           obj.write_attribute(var_name, var_value) if obj.class.columns_hash[var_name]
         end
@@ -56,7 +56,7 @@ def model
         # INSTRUCTURE: Added to allow model instances pulled out
         # of versions to still know their version number
         obj.simply_versioned_version_model = true
-        obj.send("force_version_number", self.number)
+        obj.send("force_version_number", number)
         obj
       end
     end
@@ -69,12 +69,12 @@ def model=(model)
 
     # Return the next higher numbered version, or nil if this is the last version
     def next
-      versionable.versions.next_version(self.number)
+      versionable.versions.next_version(number)
     end
 
     # Return the next lower numbered version, or nil if this is the first version
     def previous
-      versionable.versions.previous_version(self.number)
+      versionable.versions.previous_version(number)
     end
 
     # If the model has new columns that it didn't have before just return nil
@@ -98,7 +98,7 @@ def self.preload_version_number(versionables)
               AS maximum_number, v.versionable_type, v.versionable_id FROM (VALUES #{values}) AS v (versionable_id, versionable_type)"
 
             data = {}
-            rows = self.connection.select_rows(query)
+            rows = connection.select_rows(query)
             rows.each do |max, v_type, v_id|
               data[[v_type, v_id.to_i]] = max.to_i
             end
diff --git a/gems/request_context/lib/request_context/generator.rb b/gems/request_context/lib/request_context/generator.rb
index df69949054930..fecdf3d3909aa 100644
--- a/gems/request_context/lib/request_context/generator.rb
+++ b/gems/request_context/lib/request_context/generator.rb
@@ -96,7 +96,7 @@ def self.add_meta_header(name, value)
     def self.store_interaction_seconds_update(token, interaction_seconds)
       data = CanvasSecurity::PageViewJwt.decode(token)
       if data
-        self.add_meta_header("r", "#{data[:request_id]}|#{data[:created_at]}|#{interaction_seconds}")
+        add_meta_header("r", "#{data[:request_id]}|#{data[:created_at]}|#{interaction_seconds}")
       end
     end
 
@@ -111,14 +111,14 @@ def self.store_request_queue_time(header_val)
     end
 
     def self.store_request_meta(request, context)
-      self.add_meta_header("o", request.path_parameters[:controller])
-      self.add_meta_header("n", request.path_parameters[:action])
+      add_meta_header("o", request.path_parameters[:controller])
+      add_meta_header("n", request.path_parameters[:action])
       if request.request_parameters && request.request_parameters['operationName']
-        self.add_meta_header("on", request.request_parameters['operationName'])
+        add_meta_header("on", request.request_parameters['operationName'])
       end
       if context
-        self.add_meta_header("t", context.class)
-        self.add_meta_header("i", context.id)
+        add_meta_header("t", context.class)
+        add_meta_header("i", context.id)
       end
     end
 
@@ -136,10 +136,10 @@ def self.store_request_meta(request, context)
     #
     # @param [PageView] the bundle of attributes we want to map to meta headers
     def self.store_page_view_meta(page_view)
-      self.add_meta_header("x", page_view.interaction_seconds)
-      self.add_meta_header("p", page_view.participated? ? "t" : "f")
-      self.add_meta_header("e", page_view.asset_user_access_id)
-      self.add_meta_header("f", page_view.created_at.try(:utc).try(:iso8601, 2))
+      add_meta_header("x", page_view.interaction_seconds)
+      add_meta_header("p", page_view.participated? ? "t" : "f")
+      add_meta_header("e", page_view.asset_user_access_id)
+      add_meta_header("f", page_view.created_at.try(:utc).try(:iso8601, 2))
     end
 
     class << self
diff --git a/gems/tatl_tael/lib/tatl_tael/linters.rb b/gems/tatl_tael/lib/tatl_tael/linters.rb
index c337117565ac7..a511e3c7a2509 100644
--- a/gems/tatl_tael/lib/tatl_tael/linters.rb
+++ b/gems/tatl_tael/lib/tatl_tael/linters.rb
@@ -53,7 +53,7 @@ def config_for_linter(linter_class)
         # example linter_class.to_s: "TatlTael::Linters::Simple::CoffeeSpecsLinter"
         # example resulting base_config_key: "Simple/CoffeeSpecsLinter"
         base_config_key = linter_class.to_s
-                                      .sub(self.to_s, "") # rm "TatlTael::Linters"
+                                      .sub(to_s, "") # rm "TatlTael::Linters"
                                       .sub("::", "")
                                       .gsub("::", "/")
         underscore_and_symbolize_keys(config[base_config_key])
diff --git a/gems/utf8_cleaner/lib/utf8_cleaner.rb b/gems/utf8_cleaner/lib/utf8_cleaner.rb
index 2d0baf8be08b6..3b47849f4c3a5 100644
--- a/gems/utf8_cleaner/lib/utf8_cleaner.rb
+++ b/gems/utf8_cleaner/lib/utf8_cleaner.rb
@@ -37,15 +37,15 @@ def self.strip_invalid_utf8(string)
   def self.recursively_strip_invalid_utf8!(object, force_utf8 = false)
     case object
     when Hash
-      object.each_value { |o| self.recursively_strip_invalid_utf8!(o, force_utf8) }
+      object.each_value { |o| recursively_strip_invalid_utf8!(o, force_utf8) }
     when Array
-      object.each { |o| self.recursively_strip_invalid_utf8!(o, force_utf8) }
+      object.each { |o| recursively_strip_invalid_utf8!(o, force_utf8) }
     when String
       if object.encoding == Encoding::ASCII_8BIT && force_utf8
         object.force_encoding(Encoding::UTF_8)
       end
       unless object.valid_encoding?
-        object.replace(self.strip_invalid_utf8(object))
+        object.replace(strip_invalid_utf8(object))
       end
     end
   end
diff --git a/gems/workflow/lib/workflow.rb b/gems/workflow/lib/workflow.rb
index 298ae76ff7207..86370b97aa792 100644
--- a/gems/workflow/lib/workflow.rb
+++ b/gems/workflow/lib/workflow.rb
@@ -243,7 +243,7 @@ def run_action(action, *args)
     end
 
     def run_action_callback(action_name, *args)
-      self.send action_name.to_sym, *args if self.respond_to?(action_name.to_sym)
+      send action_name.to_sym, *args if respond_to?(action_name.to_sym)
     end
 
     def run_on_entry(state, prior_state, triggering_event, *args)
diff --git a/lib/account_services.rb b/lib/account_services.rb
index 4ffabd645ddfc..479599b8cfddb 100644
--- a/lib/account_services.rb
+++ b/lib/account_services.rb
@@ -88,7 +88,7 @@ def self.register_service(service_name, info_hash)
   end
 
   def self.default_allowable_services
-    res = self.allowable_services.dup
+    res = allowable_services.dup
     res.reject! { |_, info| info[:default] == false }
     res
   end
diff --git a/lib/active_record/cache_register.rb b/lib/active_record/cache_register.rb
index d505ed3c9605f..71812f849ee03 100644
--- a/lib/active_record/cache_register.rb
+++ b/lib/active_record/cache_register.rb
@@ -25,42 +25,42 @@ def base_cache_register_key_for(id_or_record)
           id = ::Shard.global_id_for(id_or_record)
           raise "invalid argument for cache clearing #{id}" if id && !id.is_a?(Integer) && !Rails.env.production?
 
-          id && "cache_register/#{self.model_name.cache_key}/#{id}"
+          id && "cache_register/#{model_name.cache_key}/#{id}"
         end
 
         def valid_cache_key_type?(key_type)
-          if Canvas::CacheRegister::ALLOWED_TYPES[self.base_class.name]&.include?(key_type.to_s)
+          if Canvas::CacheRegister::ALLOWED_TYPES[base_class.name]&.include?(key_type.to_s)
             true
           elsif ::Rails.env.production?
             false # fail gracefully
           else
-            raise "invalid cache_key type '#{key_type}' for #{self.name}"
+            raise "invalid cache_key type '#{key_type}' for #{name}"
           end
         end
 
         def prefer_multi_cache_for_key_type?(key_type)
-          !!Canvas::CacheRegister::PREFER_MULTI_CACHE_TYPES[self.base_class.name]&.include?(key_type.to_s)
+          !!Canvas::CacheRegister::PREFER_MULTI_CACHE_TYPES[base_class.name]&.include?(key_type.to_s)
         end
 
         def skip_touch_for_type?(key_type)
           valid_cache_key_type?(key_type) &&
-            Canvas::CacheRegister::MIGRATED_TYPES[self.base_class.name]&.include?(key_type.to_s) &&
-            Setting.get("revert_cache_register_migration_#{self.base_class.name.downcase}_#{key_type}", "false") != "true"
+            Canvas::CacheRegister::MIGRATED_TYPES[base_class.name]&.include?(key_type.to_s) &&
+            Setting.get("revert_cache_register_migration_#{base_class.name.downcase}_#{key_type}", "false") != "true"
         end
 
         def touch_and_clear_cache_keys(ids_or_records, *key_types)
-          unless key_types.all? { |type| self.skip_touch_for_type?(type) }
+          unless key_types.all? { |type| skip_touch_for_type?(type) }
             Array(ids_or_records).sort.each_slice(1000) do |slice|
-              self.where(id: slice).touch_all
+              where(id: slice).touch_all
             end
           end
-          self.clear_cache_keys(ids_or_records, *key_types)
+          clear_cache_keys(ids_or_records, *key_types)
         end
 
         def clear_cache_keys(ids_or_records, *key_types)
           return unless key_types.all? { |type| valid_cache_key_type?(type) } && Canvas::CacheRegister.enabled?
 
-          multi_key_types, key_types = key_types.partition { |type| Canvas::CacheRegister.can_use_multi_cache_redis? && self.prefer_multi_cache_for_key_type?(type) }
+          multi_key_types, key_types = key_types.partition { |type| Canvas::CacheRegister.can_use_multi_cache_redis? && prefer_multi_cache_for_key_type?(type) }
 
           ::Shard.partition_by_shard(Array(ids_or_records)) do |sharded_ids_or_records|
             base_keys = sharded_ids_or_records.filter_map { |item| base_cache_register_key_for(item) }
@@ -92,17 +92,17 @@ def clear_cache_keys(ids_or_records, *key_types)
         # and thus won't be terribly affected if the caching doesn't work
         def cache_key_for_id(id, key_type, skip_check: false)
           global_id = ::Shard.global_id_for(id)
-          return nil unless skip_check || (global_id && self.valid_cache_key_type?(key_type) && Canvas::CacheRegister.enabled?)
+          return nil unless skip_check || (global_id && valid_cache_key_type?(key_type) && Canvas::CacheRegister.enabled?)
 
-          base_key = self.base_cache_register_key_for(global_id)
-          prefer_multi_cache = self.prefer_multi_cache_for_key_type?(key_type)
+          base_key = base_cache_register_key_for(global_id)
+          prefer_multi_cache = prefer_multi_cache_for_key_type?(key_type)
           redis = Canvas::CacheRegister.redis(base_key, ::Shard.shard_for(global_id), prefer_multi_cache: prefer_multi_cache)
           full_key = "#{base_key}/#{key_type}"
           RequestCache.cache(full_key) do
-            now = Time.now.utc.to_s(self.cache_timestamp_format)
+            now = Time.now.utc.to_s(cache_timestamp_format)
             # try to get the timestamp for the type, set it to now if it doesn't exist
             ts = Canvas::CacheRegister.lua.run(:get_key, [full_key], [now], redis)
-            "#{self.model_name.cache_key}/#{global_id}-#{ts}"
+            "#{model_name.cache_key}/#{global_id}-#{ts}"
           end
         end
       end
@@ -112,20 +112,20 @@ def clear_cache_key(*key_types)
       end
 
       def cache_key(key_type = nil)
-        return super() if key_type.nil? || self.new_record? ||
+        return super() if key_type.nil? || new_record? ||
                           !self.class.valid_cache_key_type?(key_type) || !Canvas::CacheRegister.enabled?
 
-        self.class.cache_key_for_id(self.global_id, key_type, skip_check: true)
+        self.class.cache_key_for_id(global_id, key_type, skip_check: true)
       end
     end
 
     module Relation
       def clear_cache_keys(*key_types)
-        klass.clear_cache_keys(self.pluck(klass.primary_key), *key_types)
+        klass.clear_cache_keys(pluck(klass.primary_key), *key_types)
       end
 
       def touch_and_clear_cache_keys(*key_types)
-        klass.touch_and_clear_cache_keys(self.pluck(klass.primary_key), *key_types)
+        klass.touch_and_clear_cache_keys(pluck(klass.primary_key), *key_types)
       end
     end
   end
diff --git a/lib/active_support/cache_register.rb b/lib/active_support/cache_register.rb
index 6b9df36053c8a..39bf54f0340b9 100644
--- a/lib/active_support/cache_register.rb
+++ b/lib/active_support/cache_register.rb
@@ -43,7 +43,7 @@ def fetch_with_batched_keys(key, batch_object:, batched_keys:, skip_cache_if_dis
           end
 
           if batch_object && !opts[:force] &&
-             defined?(::ActiveSupport::Cache::RedisCacheStore) && self.is_a?(::ActiveSupport::Cache::RedisCacheStore) && Canvas::CacheRegister.enabled? &&
+             defined?(::ActiveSupport::Cache::RedisCacheStore) && is_a?(::ActiveSupport::Cache::RedisCacheStore) && Canvas::CacheRegister.enabled? &&
              batched_keys.all? { |type| batch_object.class.valid_cache_key_type?(type) }
             fetch_with_cache_register(key, batch_object, batched_keys, opts, &block)
           else
diff --git a/lib/anonymity.rb b/lib/anonymity.rb
index 7d4d0ce5b42bc..f7d93c591afaa 100644
--- a/lib/anonymity.rb
+++ b/lib/anonymity.rb
@@ -36,7 +36,7 @@ class << self
     # continuously query the database
     def generate_id(existing_ids: [])
       loop do
-        short_id = self.generate_short_id
+        short_id = generate_short_id
         break short_id unless existing_ids.include?(short_id)
       end
     end
diff --git a/lib/api.rb b/lib/api.rb
index 3a2a5b5a21a1a..d8533a78d98c5 100644
--- a/lib/api.rb
+++ b/lib/api.rb
@@ -545,10 +545,10 @@ def api_user_content(html, context = @context, user = @current_user,
     # use the host of the request if available;
     # use a placeholder host for pre-generated content, which we will replace with the request host when available;
     # otherwise let HostUrl figure out what host is appropriate
-    if self.respond_to?(:request)
+    if respond_to?(:request)
       host, protocol = get_host_and_protocol_from_request
       target_shard = Shard.current
-    elsif self.respond_to?(:use_placeholder_host?) && use_placeholder_host?
+    elsif respond_to?(:use_placeholder_host?) && use_placeholder_host?
       host = PLACEHOLDER_HOST
       protocol = PLACEHOLDER_PROTOCOL
     else
@@ -589,7 +589,7 @@ def api_user_content(html, context = @context, user = @current_user,
   # and adds context (e.g. /courses/:id/) if it is missing
   # exception: it leaves user-context file links alone
   def process_incoming_html_content(html)
-    host, port = [request.host, request.port] if self.respond_to?(:request)
+    host, port = [request.host, request.port] if respond_to?(:request)
     Html::Content.process_incoming(html, host: host, port: port)
   end
 
diff --git a/lib/api/errors.rb b/lib/api/errors.rb
index f980572d9f1d4..aaf0f98808100 100644
--- a/lib/api/errors.rb
+++ b/lib/api/errors.rb
@@ -37,7 +37,7 @@ module Errors
     self.errors = {}
 
     def self.define_error(error_id, opts)
-      self.errors[error_id] = opts
+      errors[error_id] = opts
     end
 
     define_error :deprecated_request_syntax,
diff --git a/lib/api/html/content.rb b/lib/api/html/content.rb
index ab931fb234e53..67435a8891894 100644
--- a/lib/api/html/content.rb
+++ b/lib/api/html/content.rb
@@ -26,7 +26,7 @@ class Content
       def self.process_incoming(html, host: nil, port: nil)
         return html unless html.present?
 
-        content = self.new(html, host: host, port: port)
+        content = new(html, host: host, port: port)
         # shortcut html documents that definitely don't have anything we're interested in
         return html unless content.might_need_modification?
 
@@ -36,8 +36,8 @@ def self.process_incoming(html, host: nil, port: nil)
       def self.rewrite_outgoing(html, account, url_helper, include_mobile: false, rewrite_api_urls: true)
         return html if html.blank?
 
-        self.new(html, account, include_mobile: include_mobile, rewrite_api_urls: rewrite_api_urls)
-            .rewritten_html(url_helper)
+        new(html, account, include_mobile: include_mobile, rewrite_api_urls: rewrite_api_urls)
+          .rewritten_html(url_helper)
       end
 
       attr_reader :html
diff --git a/lib/api/v1/assignment.rb b/lib/api/v1/assignment.rb
index 7b7dbb0e494ea..9a1fbb938ef32 100644
--- a/lib/api/v1/assignment.rb
+++ b/lib/api/v1/assignment.rb
@@ -602,7 +602,7 @@ def submission_types_valid?(assignment, assignment_params)
 
     if assignment_params['submission_types'].present? &&
        !assignment_params['submission_types'].all? do |s|
-         return false if s == 'wiki_page' && !self.context.try(:feature_enabled?, :conditional_release)
+         return false if s == 'wiki_page' && !context.try(:feature_enabled?, :conditional_release)
 
          API_ALLOWED_SUBMISSION_TYPES.include?(s) || (s == 'default_external_tool' && assignment.unpublished?)
        end
diff --git a/lib/api/v1/course.rb b/lib/api/v1/course.rb
index 74e3ea66c4e37..5baad6dc52389 100644
--- a/lib/api/v1/course.rb
+++ b/lib/api/v1/course.rb
@@ -181,7 +181,7 @@ def copy_status_json(import, course, user, session)
   end
 
   def add_helper_dependant_entries(hash, course, builder)
-    request = self.respond_to?(:request) ? self.request : nil
+    request = respond_to?(:request) ? self.request : nil
     hash['calendar'] = { 'ics' => "#{feeds_calendar_url(course.feed_code)}.ics" }
     hash['syllabus_body'] = api_user_content(course.syllabus_body, course) if builder.include_syllabus
     hash['html_url'] = course_url(course, :host => HostUrl.context_host(course, request.try(:host_with_port))) if builder.include_url
diff --git a/lib/api/v1/course_json.rb b/lib/api/v1/course_json.rb
index 7c0b7d72af1ca..9974c4f893b88 100644
--- a/lib/api/v1/course_json.rb
+++ b/lib/api/v1/course_json.rb
@@ -36,7 +36,7 @@ def initialize(course, user, includes, enrollments, precalculated_permissions: n
       @enrollments = enrollments
       @precalculated_permissions = precalculated_permissions
       @hash = if block_given?
-                yield(self, self.allowed_attributes, self.methods_to_send, self.permissions_to_include)
+                yield(self, allowed_attributes, methods_to_send, permissions_to_include)
               else
                 {}
               end
@@ -76,7 +76,7 @@ def to_hash
     end
 
     def self.to_hash(course, user, includes, enrollments, precalculated_permissions: nil, &block)
-      self.new(course, user, includes, enrollments, precalculated_permissions: precalculated_permissions, &block).to_hash
+      new(course, user, includes, enrollments, precalculated_permissions: precalculated_permissions, &block).to_hash
     end
 
     def clear_unneeded_fields(hash)
diff --git a/lib/api/v1/stream_item.rb b/lib/api/v1/stream_item.rb
index 44642b50a4006..97918e68792c5 100644
--- a/lib/api/v1/stream_item.rb
+++ b/lib/api/v1/stream_item.rb
@@ -140,7 +140,7 @@ def api_render_stream(opts)
           end
         end
       end
-      Api.paginate(scope, self, self.send(opts[:paginate_url], @context), default_per_page: 21).to_a
+      Api.paginate(scope, self, send(opts[:paginate_url], @context), default_per_page: 21).to_a
     end
     items.select!(&:stream_item)
     stream_item_preloads(items.map(&:stream_item))
diff --git a/lib/api_route_set.rb b/lib/api_route_set.rb
index 02d082ef9b0c5..373e9f187763d 100644
--- a/lib/api_route_set.rb
+++ b/lib/api_route_set.rb
@@ -31,7 +31,7 @@ def initialize(prefix)
   def self.draw(router, prefix = self.prefix, &block)
     @@prefixes ||= Set.new
     @@prefixes << prefix
-    route_set = self.new(prefix)
+    route_set = new(prefix)
     route_set.mapper = router
     route_set.instance_eval(&block)
   ensure
@@ -55,7 +55,7 @@ def self.segments_match(seg1, seg2)
   end
 
   def self.api_methods_for_controller_and_action(controller, action)
-    @routes ||= self.prefixes.map { |pfx| self.routes_for(pfx) }.flatten
+    @routes ||= prefixes.map { |pfx| routes_for(pfx) }.flatten
     @routes.find_all { |r| matches_controller_and_action?(r, controller, action) }
   end
 
@@ -65,7 +65,7 @@ def self.matches_controller_and_action?(route, controller, action)
 
   def method_missing(m, *a, &b)
     mapper.__send__(m, *a) {
-      self.instance_eval(&b) if b
+      instance_eval(&b) if b
     }
   end
 
diff --git a/lib/assignment_override_applicator.rb b/lib/assignment_override_applicator.rb
index 1424399eb9265..ea3bd9e47f93a 100644
--- a/lib/assignment_override_applicator.rb
+++ b/lib/assignment_override_applicator.rb
@@ -36,9 +36,9 @@ def self.assignment_overridden_for(assignment_or_quiz, user, skip_clone: false)
       return setup_overridden_clone(assignment_or_quiz)
     end
 
-    overrides = self.overrides_for_assignment_and_user(assignment_or_quiz, user)
+    overrides = overrides_for_assignment_and_user(assignment_or_quiz, user)
 
-    result_assignment_or_quiz = self.assignment_with_overrides(assignment_or_quiz, overrides)
+    result_assignment_or_quiz = assignment_with_overrides(assignment_or_quiz, overrides)
     result_assignment_or_quiz.overridden_for_user = user
 
     # students get the last overridden date that applies to them, but teachers
@@ -94,7 +94,7 @@ def self.overrides_for_assignment_and_user(assignment_or_quiz, user)
         ["overrides_for_assignment_and_user3", version_for_cache(assignment_or_quiz), assignment_or_quiz.cache_key(:availability)].cache_key,
         batch_object: user, batched_keys: [:enrollments, :groups]
       ) do
-        next [] if self.has_invalid_args?(assignment_or_quiz, user)
+        next [] if has_invalid_args?(assignment_or_quiz, user)
 
         context = assignment_or_quiz.context
 
@@ -287,7 +287,7 @@ def self.setup_overridden_clone(assignment, overrides = [])
     [:id, :updated_at, :created_at].each { |attr|
       clone[attr] = assignment.send(attr)
     }
-    self.copy_preloaded_associations_to_clone(assignment, clone)
+    copy_preloaded_associations_to_clone(assignment, clone)
     yield(clone) if block_given?
 
     clone.applied_overrides = overrides
@@ -307,10 +307,10 @@ def self.setup_overridden_clone(assignment, overrides = [])
   def self.assignment_with_overrides(assignment_or_quiz, overrides)
     unoverridden_assignment_or_quiz = assignment_or_quiz.without_overrides
 
-    self.setup_overridden_clone(unoverridden_assignment_or_quiz,
-                                overrides) do |cloned_assignment_or_quiz|
+    setup_overridden_clone(unoverridden_assignment_or_quiz,
+                           overrides) do |cloned_assignment_or_quiz|
       if overrides&.any?
-        self.collapsed_overrides(unoverridden_assignment_or_quiz, overrides).each do |field, value|
+        collapsed_overrides(unoverridden_assignment_or_quiz, overrides).each do |field, value|
           # for any times in the value set, bring them back from raw UTC into the
           # current Time.zone before placing them in the assignment
           value = value.in_time_zone if value.respond_to?(:in_time_zone) && !value.is_a?(Date)
@@ -337,14 +337,14 @@ def self.quiz_with_overrides(quiz, overrides)
   # the same collapsed assignment or quiz, regardless of the user that ended up at that
   # set of overrides.
   def self.collapsed_overrides(assignment_or_quiz, overrides)
-    cache_key = ['collapsed_overrides', assignment_or_quiz.cache_key(:availability), version_for_cache(assignment_or_quiz), self.overrides_hash(overrides)].cache_key
+    cache_key = ['collapsed_overrides', assignment_or_quiz.cache_key(:availability), version_for_cache(assignment_or_quiz), overrides_hash(overrides)].cache_key
     RequestCache.cache('collapsed_overrides', cache_key) do
       Rails.cache.fetch(cache_key) do
         overridden_data = {}
         # clone the assignment_or_quiz, apply overrides, and freeze
         [:due_at, :all_day, :all_day_date, :unlock_at, :lock_at].each do |field|
           if assignment_or_quiz.respond_to?(field)
-            value = self.send("overridden_#{field}", assignment_or_quiz, overrides)
+            value = send("overridden_#{field}", assignment_or_quiz, overrides)
             # force times to un-zoned UTC -- this will be a cached value and should
             # not care about the TZ of the user that cached it. the user's TZ will
             # be applied before it's returned.
diff --git a/lib/basic_lti/basic_outcomes.rb b/lib/basic_lti/basic_outcomes.rb
index 84a7e14741baf..8b567d65f1366 100644
--- a/lib/basic_lti/basic_outcomes.rb
+++ b/lib/basic_lti/basic_outcomes.rb
@@ -182,7 +182,7 @@ def handle_request(tool)
         # verify the lis_result_sourcedid param, which will be a canvas-signed
         # tuple of (assignment, user) to ensure that only this launch of
         # the tool is attempting to modify this data.
-        source_id = self.sourcedid
+        source_id = sourcedid
 
         begin
           assignment, user = BasicLTI::BasicOutcomes.decode_source_id(tool, source_id)
@@ -192,14 +192,14 @@ def handle_request(tool)
           return true
         end
 
-        op = self.operation_ref_identifier.underscore
+        op = operation_ref_identifier.underscore
         # Write results are disabled for concluded users, read results are still allowed
         if op != 'read_result' && !user_enrollment_active?(assignment, user)
           report_failure(:course_not_available, 'Course not available for student')
           self.body = "<#{operation_ref_identifier}Response />"
           return true
-        elsif self.respond_to?("handle_#{op}", true)
-          return self.send("handle_#{op}", tool, assignment, user)
+        elsif respond_to?("handle_#{op}", true)
+          return send("handle_#{op}", tool, assignment, user)
         end
 
         false
@@ -250,12 +250,12 @@ def report_failure(code, description)
       end
 
       def failure?
-        self.code_major == "failure"
+        code_major == "failure"
       end
 
       def handle_replace_result(tool, assignment, user)
-        text_value = self.result_score
-        score_value = self.result_total_score
+        text_value = result_score
+        score_value = result_total_score
         begin
           new_score = Float(text_value)
         rescue
diff --git a/lib/basic_lti/quizzes_next_lti_response.rb b/lib/basic_lti/quizzes_next_lti_response.rb
index 7fac8f33be202..55b7729fc46b0 100644
--- a/lib/basic_lti/quizzes_next_lti_response.rb
+++ b/lib/basic_lti/quizzes_next_lti_response.rb
@@ -85,13 +85,13 @@ def grade
     end
 
     def raw_score
-      Float(self.result_total_score)
+      Float(result_total_score)
     rescue
       nil
     end
 
     def percentage_score
-      Float(self.result_score)
+      Float(result_score)
     rescue
       nil
     end
diff --git a/lib/basic_lti/sourcedid.rb b/lib/basic_lti/sourcedid.rb
index 790fbf99cd1a9..64d52be8e43c0 100644
--- a/lib/basic_lti/sourcedid.rb
+++ b/lib/basic_lti/sourcedid.rb
@@ -74,7 +74,7 @@ def self.load!(sourcedid_string)
         assignment = course.assignments.active.find_by(id: token[:assignment_id])
       end
 
-      sourcedid = self.new(tool, course, assignment, user)
+      sourcedid = new(tool, course, assignment, user)
       sourcedid.validate!
       sourcedid
     end
diff --git a/lib/brand_config_helpers.rb b/lib/brand_config_helpers.rb
index 8581f38a55da0..802701b38ed56 100644
--- a/lib/brand_config_helpers.rb
+++ b/lib/brand_config_helpers.rb
@@ -39,9 +39,9 @@ def first_parent_brand_config
   private
 
   def brand_config_chain(include_self:)
-    chain = self.account_chain(include_site_admin: true).dup
+    chain = account_chain(include_site_admin: true).dup
     chain.shift unless include_self
-    chain.select! { |a| a.shard == self.shard }
+    chain.select! { |a| a.shard == shard }
     chain
   end
 end
diff --git a/lib/canvadocs.rb b/lib/canvadocs.rb
index bea8943f31b13..dcec6bdb8bdcf 100644
--- a/lib/canvadocs.rb
+++ b/lib/canvadocs.rb
@@ -141,7 +141,7 @@ def view(session_id)
     # Returns the json parsed response body of the call
     def api_call(method, endpoint, params = {})
       # dispatch to the right method, with the full path (/api/v2 + endpoint)
-      request = self.send("format_#{method}", "#{@url.path}/#{endpoint}", params)
+      request = send("format_#{method}", "#{@url.path}/#{endpoint}", params)
       request["Authorization"] = "Token #{token}"
       response = @http.request(request)
 
diff --git a/lib/canvas/apm.rb b/lib/canvas/apm.rb
index ee82c172eaa82..c4ce0a431f08e 100644
--- a/lib/canvas/apm.rb
+++ b/lib/canvas/apm.rb
@@ -65,8 +65,8 @@ def config
         return @_config if @_config.present?
 
         dynamic_settings = Canvas::DynamicSettings.find(tree: :private)
-        if self.canvas_cluster.present?
-          dynamic_settings = Canvas::DynamicSettings.find(tree: :private, cluster: self.canvas_cluster)
+        if canvas_cluster.present?
+          dynamic_settings = Canvas::DynamicSettings.find(tree: :private, cluster: canvas_cluster)
         end
         @_config = YAML.safe_load(dynamic_settings['datadog_apm.yml'] || '{}')
       end
@@ -74,23 +74,23 @@ def config
       def sample_rate
         return @_sample_rate if @_sample_rate.present?
 
-        @_sample_rate = self.config.fetch('sample_rate', 0.0).to_f
+        @_sample_rate = config.fetch('sample_rate', 0.0).to_f
       end
 
       def host_sample_rate
         return @_host_sample_rate if @_host_sample_rate.present?
 
-        @_host_sample_rate = self.config.fetch('host_sample_rate', 0.0).to_f
+        @_host_sample_rate = config.fetch('host_sample_rate', 0.0).to_f
       end
 
       def analytics_enabled?
         return @_app_analytics_enabled unless @_app_analytics_enabled.nil?
 
-        @_app_analytics_enabled = self.config.fetch('app_analytics_enabled', false)
+        @_app_analytics_enabled = config.fetch('app_analytics_enabled', false)
       end
 
       def configured?
-        self.sample_rate > 0.0 && host_chosen?
+        sample_rate > 0.0 && host_chosen?
       end
 
       def host_chosen?
@@ -116,17 +116,17 @@ def get_sampling_decision(string_input, rate, interval)
       end
 
       def rate_sampler
-        Datadog::RateSampler.new(self.sample_rate)
+        Datadog::RateSampler.new(sample_rate)
       end
 
       def enable_apm!
-        sampler = self.rate_sampler
+        sampler = rate_sampler
         debug_mode = @enable_debug_mode.presence || false
         Datadog.configure do |c|
           # this is filtered on the datadog UI side
           # to make sure we don't analyze _everything_
           # which would be very expensive
-          c.analytics_enabled = self.analytics_enabled?
+          c.analytics_enabled = analytics_enabled?
           c.tracer sampler: sampler, debug: debug_mode
           c.use :aws
           c.use :faraday
@@ -139,11 +139,11 @@ def enable_apm!
       end
 
       def configure_apm!
-        self.enable_apm! if self.configured?
+        enable_apm! if configured?
       end
 
       def annotate_trace(shard, root_account, request_context_id, current_user)
-        return unless self.configured?
+        return unless configured?
 
         apm_root_span = tracer.active_root_span
         return if apm_root_span.blank?
@@ -171,7 +171,7 @@ def annotate_trace(shard, root_account, request_context_id, current_user)
       # See datadog examples here:
       # http://gems.datadoghq.com/trace/docs/#Manual_Instrumentation
       def tracer
-        return Canvas::Apm::StubTracer.instance unless self.configured?
+        return Canvas::Apm::StubTracer.instance unless configured?
 
         @tracer || Datadog.tracer
       end
diff --git a/lib/canvas/draft_state_validations.rb b/lib/canvas/draft_state_validations.rb
index 1063d48f44bbd..8c096b0a28596 100644
--- a/lib/canvas/draft_state_validations.rb
+++ b/lib/canvas/draft_state_validations.rb
@@ -26,12 +26,12 @@ def self.included(base)
     end
 
     def validate_draft_state_change
-      old_draft_state, new_draft_state = self.changes['workflow_state']
+      old_draft_state, new_draft_state = changes['workflow_state']
       return if old_draft_state == new_draft_state
 
       if new_draft_state == 'unpublished' && has_student_submissions?
-        self.errors.add :workflow_state, I18n.t('#quizzes.cant_unpublish_when_students_submit',
-                                                "Can't unpublish if there are student submissions")
+        errors.add :workflow_state, I18n.t('#quizzes.cant_unpublish_when_students_submit',
+                                           "Can't unpublish if there are student submissions")
       end
     end
   end
diff --git a/lib/canvas/errors/log_entry.rb b/lib/canvas/errors/log_entry.rb
index d6ea6fac7da88..fb5a4f6542918 100644
--- a/lib/canvas/errors/log_entry.rb
+++ b/lib/canvas/errors/log_entry.rb
@@ -33,7 +33,7 @@ class LogEntry
       # on a condition and write a message if a surprising
       # thing happens
       def self.write(exception, data, level = :error)
-        msg = self.new(exception, data).message
+        msg = new(exception, data).message
         Rails.logger.send(level, msg)
       end
 
diff --git a/lib/canvas/migration/archive.rb b/lib/canvas/migration/archive.rb
index 12c9ee43e19a3..c8528de470ef2 100644
--- a/lib/canvas/migration/archive.rb
+++ b/lib/canvas/migration/archive.rb
@@ -112,7 +112,7 @@ def unzipped_file_path
     end
 
     def package_root
-      @package_root ||= PackageRoot.new(self.unzipped_file_path)
+      @package_root ||= PackageRoot.new(unzipped_file_path)
     end
 
     def get_converter
@@ -160,16 +160,16 @@ def delete_unzipped_archive
     # If the file is a zip file, unzip it, if it's an xml file, copy
     # it into the directory with the given file name
     def prepare_cartridge_file(file_name = 'imsmanifest.xml')
-      if self.path.ends_with?('xml')
-        FileUtils.cp(self.path, package_root.item_path(file_name))
+      if path.ends_with?('xml')
+        FileUtils.cp(path, package_root.item_path(file_name))
       else
         unzip_archive
       end
     end
 
     def delete_unzipped_file
-      if File.exist?(self.unzipped_file_path)
-        FileUtils.rm_rf(self.unzipped_file_path)
+      if File.exist?(unzipped_file_path)
+        FileUtils.rm_rf(unzipped_file_path)
       end
     end
 
diff --git a/lib/canvas/migration/external_content/migrator.rb b/lib/canvas/migration/external_content/migrator.rb
index 1e0be766e1a53..64786ed5f4cca 100644
--- a/lib/canvas/migration/external_content/migrator.rb
+++ b/lib/canvas/migration/external_content/migrator.rb
@@ -25,10 +25,10 @@ def registered_services
       end
 
       def register_service(key, service)
-        raise "service with the key #{key} is already registered" if self.registered_services[key] && self.registered_services[key] != service
+        raise "service with the key #{key} is already registered" if registered_services[key] && registered_services[key] != service
 
         Canvas::Migration::ExternalContent::ServiceInterface.validate_service!(service)
-        self.registered_services[key] = service
+        registered_services[key] = service
       end
 
       # tells the services to begin exporting
@@ -36,7 +36,7 @@ def register_service(key, service)
       def begin_exports(course, opts = {})
         pending_exports = {}
         pending_exports.merge!(Lti::ContentMigrationService.begin_exports(course, opts)) if Lti::ContentMigrationService.enabled?
-        self.registered_services.each do |key, service|
+        registered_services.each do |key, service|
           if service.applies_to_course?(course)
             begin
               if (export = service.begin_export(course, opts))
@@ -102,7 +102,7 @@ def export_completed?(pending_export, key)
         if pending_export.respond_to?(:export_completed?)
           pending_export.export_completed?
         else
-          self.registered_services[key].export_completed?(pending_export)
+          registered_services[key].export_completed?(pending_export)
         end
       end
 
@@ -110,7 +110,7 @@ def retrieve_export_data(pending_export, key)
         if pending_export.respond_to?(:retrieve_export)
           pending_export.retrieve_export
         else
-          self.registered_services[key].retrieve_export(pending_export)
+          registered_services[key].retrieve_export(pending_export)
         end
       end
 
@@ -138,7 +138,7 @@ def send_imported_content(migration, imported_content)
         if Lti::ContentMigrationService::KEY_REGEX.match?(key)
           Lti::ContentMigrationService.importer_for(key)
         else
-          self.registered_services[key]
+          registered_services[key]
         end
       end
 
@@ -149,7 +149,7 @@ def ensure_imports_completed(pending_imports)
           if import_data.respond_to?(:import_completed?)
             import_data.import_completed?
           else
-            self.registered_services[key].import_completed?(import_data)
+            registered_services[key].import_completed?(import_data)
           end
         end
       end
diff --git a/lib/canvas/plugin.rb b/lib/canvas/plugin.rb
index 88840d34b1d8c..3b168b138a107 100644
--- a/lib/canvas/plugin.rb
+++ b/lib/canvas/plugin.rb
@@ -48,7 +48,7 @@ def initialize(id, tag = nil)
 
     # custom serialization, since the meta can containt procs
     def _dump(_depth)
-      self.id.to_s
+      id.to_s
     end
 
     def self._load(str)
@@ -56,7 +56,7 @@ def self._load(str)
     end
 
     def encode_with(coder)
-      coder['id'] = self.id.to_s
+      coder['id'] = id.to_s
     end
 
     Psych.add_domain_type("ruby/object", "Canvas::Plugin") do |_type, val|
@@ -70,7 +70,7 @@ def default_settings
     end
 
     def saved_settings
-      PluginSetting.settings_for_plugin(self.id, self)
+      PluginSetting.settings_for_plugin(id, self)
     end
 
     def settings
@@ -78,7 +78,7 @@ def settings
     end
 
     def enabled?
-      ps = PluginSetting.cached_plugin_setting(self.id)
+      ps = PluginSetting.cached_plugin_setting(id)
       return false unless ps
 
       ps.valid_settings? && ps.enabled?
@@ -156,12 +156,12 @@ def validate_settings(plugin_setting, settings)
         end
         res = validator_module.validate(settings, plugin_setting)
         if res.is_a?(Hash)
-          plugin_setting.settings = (plugin_setting.settings || self.default_settings || {}).with_indifferent_access.merge(res || {})
+          plugin_setting.settings = (plugin_setting.settings || default_settings || {}).with_indifferent_access.merge(res || {})
         else
           false
         end
       else
-        plugin_setting.settings = (plugin_setting.settings || self.default_settings || {}).with_indifferent_access.merge(settings || {})
+        plugin_setting.settings = (plugin_setting.settings || default_settings || {}).with_indifferent_access.merge(settings || {})
       end
     end
 
diff --git a/lib/canvas/plugins/ticketing_system/custom_error.rb b/lib/canvas/plugins/ticketing_system/custom_error.rb
index 8b9d6b8fe0dc1..de56c2e82d91c 100644
--- a/lib/canvas/plugins/ticketing_system/custom_error.rb
+++ b/lib/canvas/plugins/ticketing_system/custom_error.rb
@@ -39,32 +39,32 @@ class CustomError < DelegateClass(::ErrorReport)
     # returns Hash
     def to_document
       {
-        subject: self.subject,
-        description: self.comments,
-        report_type: self.report_type,
-        error_message: self.message,
-        perceived_severity: self.user_severity,
-        account_id: self.account_id,
-        account_domain: self.account_domain_value,
-        report_origin_url: self.url,
+        subject: subject,
+        description: comments,
+        report_type: report_type,
+        error_message: message,
+        perceived_severity: user_severity,
+        account_id: account_id,
+        account_domain: account_domain_value,
+        report_origin_url: url,
         reporter: {
-          canvas_id: self.user_id.to_s,
-          email: self.guess_email,
-          name: self.user_name,
-          role: self.user_roles,
-          become_user_uri: self.become_user_id_uri,
-          environment: self.http_env
+          canvas_id: user_id.to_s,
+          email: guess_email,
+          name: user_name,
+          role: user_roles,
+          become_user_uri: become_user_id_uri,
+          environment: http_env
         },
         canvas_details: {
-          request_context_id: self.request_context_id,
-          error_report_id: self.id,
-          sub_account: self.sub_account_tag,
+          request_context_id: request_context_id,
+          error_report_id: id,
+          sub_account: sub_account_tag,
         }
       }
     end
 
     def sub_account_tag(asset_manager = ::Context, expected_type = Course)
-      if (context_string = self.data['context_asset_string'])
+      if (context_string = data['context_asset_string'])
         context = asset_manager.find_by_asset_string(context_string)
         if context.is_a? expected_type
           "subaccount_#{context.account_id}"
@@ -77,27 +77,27 @@ def sub_account_tag(asset_manager = ::Context, expected_type = Course)
     # error report backtrace attribute, but if there's nothing
     # recognizable there it will just assume it's an ERROR
     def report_type(default_value = 'ERROR')
-      return default_value unless self.backtrace.present?
+      return default_value unless backtrace.present?
 
-      first_line = self.backtrace.split("\n").first
+      first_line = backtrace.split("\n").first
       match = first_line.match(/^Posted as[^_]*_([A-Z]*)_/) if first_line.present?
       (match.nil? ? nil : match[1]) || default_value
     end
 
     def user_severity
-      (self.data.is_a?(Hash) && self.data['user_perceived_severity']) || ''
+      (data.is_a?(Hash) && data['user_perceived_severity']) || ''
     end
 
     def user_roles
-      self.data.is_a?(Hash) ? self.data['user_roles'] : nil
+      data.is_a?(Hash) ? data['user_roles'] : nil
     end
 
     def account_domain_value
-      self.account.try(:domain)
+      account.try(:domain)
     end
 
     def user_name
-      self.user.try(:name) || "Unknown User"
+      user.try(:name) || "Unknown User"
     end
 
     def become_user_id_uri
@@ -125,7 +125,7 @@ def pretty_http_env
     end
 
     def raw_report
-      self.__getobj__
+      __getobj__
     end
   end
 end
diff --git a/lib/canvas/security/login_registry.rb b/lib/canvas/security/login_registry.rb
index feb1027f049f2..1d8b2a8ca9dd0 100644
--- a/lib/canvas/security/login_registry.rb
+++ b/lib/canvas/security/login_registry.rb
@@ -97,7 +97,7 @@ def self.failed_login!(pseudonym, ip)
 
     # returns time in seconds
     def self.time_until_login_allowed(pseudonym, ip)
-      if self.allow_login_attempt?(pseudonym, ip)
+      if allow_login_attempt?(pseudonym, ip)
         0
       else
         Canvas.redis.ttl(login_attempts_key(pseudonym))
diff --git a/lib/cc/exporter/epub/exportable.rb b/lib/cc/exporter/epub/exportable.rb
index 222ead683543f..d2aa176a42307 100644
--- a/lib/cc/exporter/epub/exportable.rb
+++ b/lib/cc/exporter/epub/exportable.rb
@@ -20,7 +20,7 @@
 module CC::Exporter::Epub
   module Exportable
     def content_cartridge
-      self.attachment
+      attachment
     end
 
     def convert_to_epub
diff --git a/lib/cc/exporter/web_zip/exportable.rb b/lib/cc/exporter/web_zip/exportable.rb
index 6115bfe9d6b44..9607e522cd004 100644
--- a/lib/cc/exporter/web_zip/exportable.rb
+++ b/lib/cc/exporter/web_zip/exportable.rb
@@ -20,7 +20,7 @@
 module CC::Exporter::WebZip
   module Exportable
     def content_cartridge
-      self.attachment
+      attachment
     end
 
     def create_zip(exporter, progress_key)
@@ -29,7 +29,7 @@ def create_zip(exporter, progress_key)
 
     def convert_to_offline_web_zip(progress_key)
       exporter = CC::Exporter::WebZip::Exporter.new(content_cartridge.open, false, :web_zip,
-                                                    global_identifiers: self.content_export.global_identifiers?)
+                                                    global_identifiers: content_export.global_identifiers?)
       zip = create_zip(exporter, progress_key)
       file_path = zip.create
 
diff --git a/lib/cc/importer/standard/converter.rb b/lib/cc/importer/standard/converter.rb
index 2276f01f94664..01dac6974b217 100644
--- a/lib/cc/importer/standard/converter.rb
+++ b/lib/cc/importer/standard/converter.rb
@@ -42,7 +42,7 @@ def initialize(settings)
       @resources = {}
       @file_path_migration_id = {}
       @resource_nodes_for_flat_manifest = {}
-      @convert_html_to_pages = self.content_migration&.context&.feature_enabled?(:common_cartridge_page_conversion)
+      @convert_html_to_pages = content_migration&.context&.feature_enabled?(:common_cartridge_page_conversion)
     end
 
     # exports the package into the intermediary json
diff --git a/lib/cc/resource.rb b/lib/cc/resource.rb
index 6ca5ade2140fe..84f04bff80afc 100644
--- a/lib/cc/resource.rb
+++ b/lib/cc/resource.rb
@@ -88,7 +88,7 @@ def create_resources
     def run_and_set_progress(method, progress, fail_message, *args)
       res = nil
       begin
-        res = self.send(method, *args)
+        res = send(method, *args)
       rescue
         add_error(fail_message, $!)
       end
diff --git a/lib/content_notices.rb b/lib/content_notices.rb
index 17cb947cc704d..6350bd1326d97 100644
--- a/lib/content_notices.rb
+++ b/lib/content_notices.rb
@@ -54,7 +54,7 @@ def self.included(base)
   end
 
   def cn_cache_key(tag)
-    ["content_notice_present", tag, self.asset_string].cache_key
+    ["content_notice_present", tag, asset_string].cache_key
   end
 
   # add a notice to this context. if the notice with the given tag is already active for the context,
diff --git a/lib/copy_authorized_links.rb b/lib/copy_authorized_links.rb
index b13f2e537aa7b..92f26f6d82f29 100644
--- a/lib/copy_authorized_links.rb
+++ b/lib/copy_authorized_links.rb
@@ -38,10 +38,10 @@ def repair_malformed_links(user)
       columns.each do |column|
         next if column == :custom
 
-        html = self.read_attribute(column) rescue nil
+        html = read_attribute(column) rescue nil
         next if html.blank?
 
-        context, inferred_user = self.instance_eval(&block) if block
+        context, inferred_user = instance_eval(&block) if block
         user = @copy_authorized_links_override_user || inferred_user
         re = Regexp.new("/#{context.class.to_s.pluralize.underscore}/#{context.id}/files/(\\d+)")
         ids = []
@@ -51,22 +51,22 @@ def repair_malformed_links(user)
         Attachment.where(id: ids.uniq).each do |file|
           html = html.gsub(Regexp.new("/#{context.class.to_s.pluralize.underscore}/#{context.id}/files/#{file.id}"), "/#{file.context_type.pluralize.underscore}/#{file.context_id}/files/#{file.id}")
         end
-        self.write_attribute(column, html) if html.present?
+        write_attribute(column, html) if html.present?
       end
-      self.save
+      save
     end
 
     def copy_authorized_links_to_context
       columns = (self.class.copy_authorized_links_columns || []).compact
       columns.each do |column|
         if column == :custom
-          if self.respond_to?(:copy_authorized_content_custom_column)
-            self.copy_authorized_content_custom_column(context, user)
+          if respond_to?(:copy_authorized_content_custom_column)
+            copy_authorized_content_custom_column(context, user)
           end
         else
-          html = self.read_attribute(column) rescue nil
+          html = read_attribute(column) rescue nil
           if html && !html.empty?
-            self.write_attribute(column, html) if html && !html.empty?
+            write_attribute(column, html) if html && !html.empty?
           end
         end
       end
diff --git a/lib/course_link_validator.rb b/lib/course_link_validator.rb
index 5342a280a1622..4b12680b67608 100644
--- a/lib/course_link_validator.rb
+++ b/lib/course_link_validator.rb
@@ -39,7 +39,7 @@ def self.queue_course(course)
   end
 
   def self.process(progress)
-    validator = self.new(progress.context)
+    validator = new(progress.context)
     validator.check_course(progress)
     progress.set_results({ :issues => validator.issues, :completed_at => Time.now.utc, :version => 2 })
   rescue
@@ -62,24 +62,24 @@ def initialize(course)
   # this is where the magic happens
   def check_course(progress)
     # Course card image
-    if self.course.image_url.present?
-      find_invalid_link(self.course.image_url) do |link|
-        self.issues << { :name => I18n.t("Course Card Image"), :type => :course_card_image,
-                         :content_url => "/courses/#{self.course.id}/settings",
-                         :invalid_links => [link.merge(:image => true)] }
+    if course.image_url.present?
+      find_invalid_link(course.image_url) do |link|
+        issues << { :name => I18n.t("Course Card Image"), :type => :course_card_image,
+                    :content_url => "/courses/#{course.id}/settings",
+                    :invalid_links => [link.merge(:image => true)] }
       end
       progress.update_completion! 1
     end
 
     # Syllabus
-    find_invalid_links(self.course.syllabus_body) do |links|
-      self.issues << { :name => I18n.t(:syllabus, "Course Syllabus"), :type => :syllabus,
-                       :content_url => "/courses/#{self.course.id}/assignments/syllabus" }.merge(:invalid_links => links)
+    find_invalid_links(course.syllabus_body) do |links|
+      issues << { :name => I18n.t(:syllabus, "Course Syllabus"), :type => :syllabus,
+                  :content_url => "/courses/#{course.id}/assignments/syllabus" }.merge(:invalid_links => links)
     end
     progress.update_completion! 5
 
     # Assessment questions
-    self.course.assessment_questions.active.each do |aq|
+    course.assessment_questions.active.each do |aq|
       next if aq.assessment_question_bank.deleted?
 
       check_question(aq)
@@ -87,53 +87,53 @@ def check_course(progress)
     progress.update_completion! 15
 
     # Assignments
-    self.course.assignments.active.each do |assignment|
+    course.assignments.active.each do |assignment|
       next if assignment.quiz || assignment.discussion_topic
 
       find_invalid_links(assignment.description) do |links|
-        self.issues << { :name => assignment.title, :type => :assignment,
-                         :content_url => "/courses/#{self.course.id}/assignments/#{assignment.id}" }.merge(:invalid_links => links)
+        issues << { :name => assignment.title, :type => :assignment,
+                    :content_url => "/courses/#{course.id}/assignments/#{assignment.id}" }.merge(:invalid_links => links)
       end
     end
     progress.update_completion! 25
 
     # Calendar events
-    self.course.calendar_events.active.each do |event|
+    course.calendar_events.active.each do |event|
       find_invalid_links(event.description) do |links|
-        self.issues << { :name => event.title, :type => :calendar_event,
-                         :content_url => "/courses/#{self.course.id}/calendar_events/#{event.id}" }.merge(:invalid_links => links)
+        issues << { :name => event.title, :type => :calendar_event,
+                    :content_url => "/courses/#{course.id}/calendar_events/#{event.id}" }.merge(:invalid_links => links)
       end
     end
     progress.update_completion! 35
 
     # Discussion topics
-    self.course.discussion_topics.active.each do |topic|
+    course.discussion_topics.active.each do |topic|
       find_invalid_links(topic.message) do |links|
-        self.issues << { :name => topic.title, :type => :discussion_topic,
-                         :content_url => "/courses/#{self.course.id}/discussion_topics/#{topic.id}" }.merge(:invalid_links => links)
+        issues << { :name => topic.title, :type => :discussion_topic,
+                    :content_url => "/courses/#{course.id}/discussion_topics/#{topic.id}" }.merge(:invalid_links => links)
       end
     end
     progress.update_completion! 55
 
     # External URL Module items (almost forgot about these)
     invalid_module_links = {}
-    self.course.context_module_tags.not_deleted.where(:content_type => "ExternalUrl").preload(:context_module).each do |ct|
+    course.context_module_tags.not_deleted.where(:content_type => "ExternalUrl").preload(:context_module).each do |ct|
       find_invalid_link(ct.url) do |invalid_link|
         (invalid_module_links[ct.context_module] ||= []) << invalid_link.merge(:link_text => ct.title)
       end
     end
     invalid_module_links.each do |mod, links|
-      self.issues << { :name => mod.name, :type => :module,
-                       :content_url => "/courses/#{self.course.id}/modules#module_#{mod.id}" }.merge(:invalid_links => links)
+      issues << { :name => mod.name, :type => :module,
+                  :content_url => "/courses/#{course.id}/modules#module_#{mod.id}" }.merge(:invalid_links => links)
     end
 
     progress.update_completion! 65
 
     # Quizzes
-    self.course.quizzes.active.each do |quiz|
+    course.quizzes.active.each do |quiz|
       find_invalid_links(quiz.description) do |links|
-        self.issues << { :name => quiz.title, :type => :quiz,
-                         :content_url => "/courses/#{self.course.id}/quizzes/#{quiz.id}" }.merge(:invalid_links => links)
+        issues << { :name => quiz.title, :type => :quiz,
+                    :content_url => "/courses/#{course.id}/quizzes/#{quiz.id}" }.merge(:invalid_links => links)
       end
       quiz.quiz_questions.active.each do |qq|
         check_question(qq)
@@ -142,10 +142,10 @@ def check_course(progress)
     progress.update_completion! 85
 
     # Wiki pages
-    self.course.wiki_pages.not_deleted.each do |page|
+    course.wiki_pages.not_deleted.each do |page|
       find_invalid_links(page.body) do |links|
-        self.issues << { :name => page.title, :type => :wiki_page,
-                         :content_url => "/courses/#{self.course.id}/pages/#{page.url}" }.merge(:invalid_links => links)
+        issues << { :name => page.title, :type => :wiki_page,
+                    :content_url => "/courses/#{course.id}/pages/#{page.url}" }.merge(:invalid_links => links)
       end
     end
     progress.update_completion! 99
@@ -174,10 +174,10 @@ def check_question(question)
       case question
       when AssessmentQuestion
         hash[:type] = :assessment_question
-        hash[:content_url] = "/courses/#{self.course.id}/question_banks/#{question.assessment_question_bank_id}#question_#{question.id}_question_text"
+        hash[:content_url] = "/courses/#{course.id}/question_banks/#{question.assessment_question_bank_id}#question_#{question.id}_question_text"
       when Quizzes::QuizQuestion
         hash[:type] = :quiz_question
-        hash[:content_url] = "/courses/#{self.course.id}/quizzes/#{question.quiz_id}/take?preview=1#question_#{question.id}"
+        hash[:content_url] = "/courses/#{course.id}/quizzes/#{question.quiz_id}/take?preview=1#question_#{question.id}"
       end
       issues << hash
     end
@@ -214,11 +214,11 @@ def find_invalid_links(html)
   def find_invalid_link(url)
     return if url.start_with?('mailto:')
 
-    unless (result = self.visited_urls[url])
+    unless (result = visited_urls[url])
       begin
-        if ImportedHtmlConverter.relative_url?(url) || (self.domain_regex && url.match(self.domain_regex))
+        if ImportedHtmlConverter.relative_url?(url) || (domain_regex && url.match(domain_regex))
           result = if valid_route?(url)
-                     if url.match(%r{/courses/(\d+)}) && self.course.id.to_s != $1
+                     if url.match(%r{/courses/(\d+)}) && course.id.to_s != $1
                        :course_mismatch
                      else
                        check_object_status(url)
@@ -235,7 +235,7 @@ def find_invalid_link(url)
         result = :unparsable
       end
       result ||= :success
-      self.visited_urls[url] = result
+      visited_urls[url] = result
     end
 
     unless result == :success
diff --git a/lib/csv_with_i18n.rb b/lib/csv_with_i18n.rb
index e5d9ebd2e794f..e2509d7183d31 100644
--- a/lib/csv_with_i18n.rb
+++ b/lib/csv_with_i18n.rb
@@ -22,7 +22,7 @@ class CSVWithI18n < CSV
   def initialize(data, **options)
     @include_bom = options.delete(:include_bom)
     super(data, **options)
-    raise 'include_bom and write_headers cannot both be true' if self.write_headers? && @include_bom
+    raise 'include_bom and write_headers cannot both be true' if write_headers? && @include_bom
   end
 
   def <<(row)
diff --git a/lib/cuty_capt.rb b/lib/cuty_capt.rb
index eddcc068d0da1..102dcb8aa645d 100644
--- a/lib/cuty_capt.rb
+++ b/lib/cuty_capt.rb
@@ -62,7 +62,7 @@ def self.config
     end
     setting = setting.symbolize_keys
     @@config = CUTYCAPT_DEFAULTS.merge(setting).with_indifferent_access
-    self.process_config
+    process_config
     @@config = nil unless @@config[:path] || @@config[:screencap_service]
     @@config
   end
@@ -85,7 +85,7 @@ def self.logger
   end
 
   def self.enabled?
-    !self.config.nil?
+    !config.nil?
   end
 
   def self.verify_url(url)
@@ -120,7 +120,7 @@ def self.cuty_arguments(path, url, img_file, format, delay, timeout, lang)
 
   def self.snapshot_url(url)
     return nil unless (config = self.config)
-    return nil unless self.verify_url(url)
+    return nil unless verify_url(url)
 
     format = "png"
 
@@ -179,7 +179,7 @@ def self.snapshot_url(url)
 
   def self.snapshot_attachment_for_url(url)
     attachment = nil
-    self.snapshot_url(url) do |file_path|
+    snapshot_url(url) do |file_path|
       # this is a really odd way to get Attachment the data it needs, which
       # should probably be remedied at some point
       attachment = Attachment.new(:uploaded_data => Rack::Test::UploadedFile.new(file_path, "image/png"))
diff --git a/lib/data_fixup/copy_built_in_roles_by_root_account.rb b/lib/data_fixup/copy_built_in_roles_by_root_account.rb
index 8dda96755e326..058bf21c4f66c 100644
--- a/lib/data_fixup/copy_built_in_roles_by_root_account.rb
+++ b/lib/data_fixup/copy_built_in_roles_by_root_account.rb
@@ -65,7 +65,7 @@ def self.run
 
       Enrollment.find_ids_in_ranges(:batch_size => 100_000) do |start_at, end_at|
         # these are taking long enough that we should batch them
-        self.move_roles_for_enrollments(old_role_ids, start_at, end_at)
+        move_roles_for_enrollments(old_role_ids, start_at, end_at)
       end
     end
   end
diff --git a/lib/data_fixup/init_new_grade_history_audit_log_indexes.rb b/lib/data_fixup/init_new_grade_history_audit_log_indexes.rb
index 349d379b4b052..e623d1cdaa4c4 100644
--- a/lib/data_fixup/init_new_grade_history_audit_log_indexes.rb
+++ b/lib/data_fixup/init_new_grade_history_audit_log_indexes.rb
@@ -70,7 +70,7 @@ def read_and_process_batch(starting_key, index_entries)
       result.fetch do |row|
         last_id = row['id']
         INDEX_METHODS.each do |method|
-          result = self.send(method, row)
+          result = send(method, row)
           index_entries << result if result
         end
       end
diff --git a/lib/data_fixup/migrate_messages_to_partitions.rb b/lib/data_fixup/migrate_messages_to_partitions.rb
index 56750508df51d..c184bb6d23e70 100644
--- a/lib/data_fixup/migrate_messages_to_partitions.rb
+++ b/lib/data_fixup/migrate_messages_to_partitions.rb
@@ -34,7 +34,7 @@ def self.run(batch_size: 1000, last_run_date_threshold: nil)
     if partman.migrate_data_to_partitions(timeout: 5.minutes, batch_size: batch_size)
       GuardRail.activate(:deploy) { Message.connection.update("TRUNCATE ONLY #{Message.quoted_table_name}") }
     else
-      self.requeue(batch_size: batch_size, last_run_date_threshold: min_date_threshold) # timed out
+      requeue(batch_size: batch_size, last_run_date_threshold: min_date_threshold) # timed out
     end
   end
 
diff --git a/lib/dates_overridable.rb b/lib/dates_overridable.rb
index 99d663da2f348..714db56a4d483 100644
--- a/lib/dates_overridable.rb
+++ b/lib/dates_overridable.rb
@@ -182,7 +182,7 @@ def observed_student_due_dates(user, observed_student_ids = nil)
                           ObserverEnrollment.observed_students(context, user).keys
                         end
     dates = observed_students.map do |student|
-      self.all_dates_visible_to(student)
+      all_dates_visible_to(student)
     end
     dates.flatten.uniq
   end
@@ -221,10 +221,10 @@ def formatted_dates_hash(dates)
 
   def due_date_hash
     hash = { :due_at => due_at, :unlock_at => unlock_at, :lock_at => lock_at }
-    if self.is_a?(Assignment)
+    if is_a?(Assignment)
       hash[:all_day] = all_day
       hash[:all_day_date] = all_day_date
-    elsif self.assignment
+    elsif assignment
       hash[:all_day] = assignment.all_day
       hash[:all_day_date] = assignment.all_day_date
     end
@@ -246,27 +246,27 @@ def base_due_date_hash
   def context_module_tag_info(user, context, user_is_admin: false, has_submission:)
     return {} unless user
 
-    self.association(:context).target ||= context
+    association(:context).target ||= context
     tag_info = Rails.cache.fetch_with_batched_keys(
       ["context_module_tag_info3", user.cache_key(:enrollments), user.cache_key(:groups)].cache_key,
       batch_object: self, batched_keys: :availability
     ) do
       hash = {}
-      if user_is_admin && self.has_too_many_overrides
+      if user_is_admin && has_too_many_overrides
         hash[:has_many_overrides] = true
-      elsif self.multiple_due_dates_apply_to?(user)
+      elsif multiple_due_dates_apply_to?(user)
         hash[:vdd_tooltip] = OverrideTooltipPresenter.new(self, user).as_json
-      elsif (due_date = self.overridden_for(user).due_at) ||
+      elsif (due_date = overridden_for(user).due_at) ||
             (user_is_admin && (due_date = all_due_dates.dig(0, :due_at)))
         hash[:due_date] = due_date
       end
       hash
     end
-    tag_info[:points_possible] = self.points_possible
+    tag_info[:points_possible] = points_possible
 
     if user && tag_info[:due_date]
       if tag_info[:due_date] < Time.now
-        if self.is_a?(Quizzes::Quiz) || (self.is_a?(Assignment) && expects_submission?)
+        if is_a?(Quizzes::Quiz) || (is_a?(Assignment) && expects_submission?)
           tag_info[:past_due] = true unless has_submission
         end
       end
diff --git a/lib/differentiable_assignment.rb b/lib/differentiable_assignment.rb
index f40c8bbd7430a..332ec2f9ec350 100644
--- a/lib/differentiable_assignment.rb
+++ b/lib/differentiable_assignment.rb
@@ -19,10 +19,10 @@
 
 module DifferentiableAssignment
   def differentiated_assignments_applies?
-    if self.is_a?(Assignment) || Quizzes::Quiz.class_names.include?(self.class_name)
-      self.only_visible_to_overrides
-    elsif self.assignment
-      self.assignment.only_visible_to_overrides
+    if is_a?(Assignment) || Quizzes::Quiz.class_names.include?(class_name)
+      only_visible_to_overrides
+    elsif assignment
+      assignment.only_visible_to_overrides
     else
       false
     end
@@ -31,24 +31,24 @@ def differentiated_assignments_applies?
   def visible_to_user?(user, opts = {})
     # slightly redundant conditional, but avoiding unnecessary lookups
     return true if opts[:differentiated_assignments] == false ||
-                   (opts[:differentiated_assignments] == true && !self.only_visible_to_overrides) ||
-                   !self.differentiated_assignments_applies? # checks if DA enabled on course and then only_visible_to_overrides
+                   (opts[:differentiated_assignments] == true && !only_visible_to_overrides) ||
+                   !differentiated_assignments_applies? # checks if DA enabled on course and then only_visible_to_overrides
 
     # will add users if observer and only filter based on DA when necessary (not for teachers/some observers)
-    visible_instances = DifferentiableAssignment.filter([self], user, self.context) do |_, user_ids|
+    visible_instances = DifferentiableAssignment.filter([self], user, context) do |_, user_ids|
       conditions = { user_id: user_ids }
-      conditions[column_name] = self.id
+      conditions[column_name] = id
       visibility_view.where(conditions)
     end
     visible_instances.any?
   end
 
   def visibility_view
-    self.is_a?(Assignment) ? AssignmentStudentVisibility : Quizzes::QuizStudentVisibility
+    is_a?(Assignment) ? AssignmentStudentVisibility : Quizzes::QuizStudentVisibility
   end
 
   def column_name
-    self.is_a?(Assignment) ? :assignment_id : :quiz_id
+    is_a?(Assignment) ? :assignment_id : :quiz_id
   end
 
   # will not filter the collection for teachers, will for non-observer students
@@ -69,7 +69,7 @@ def self.filter(collection, user, context, opts = {})
   # can filter scope of Assignments, DiscussionTopics, Quizzes, or ContentTags
   def self.scope_filter(scope, user, context, opts = {})
     context.shard.activate do
-      self.filter(scope, user, context, opts) do |filtered_scope, user_ids|
+      filter(scope, user, context, opts) do |filtered_scope, user_ids|
         filtered_scope.visible_to_students_in_course_with_da(user_ids, context.id)
       end
     end
diff --git a/lib/due_date_cacher.rb b/lib/due_date_cacher.rb
index fb0128d9f3c6b..780f66aabe62d 100644
--- a/lib/due_date_cacher.rb
+++ b/lib/due_date_cacher.rb
@@ -112,7 +112,7 @@ def self.recompute_course(course, assignments: nil, inst_jobs_opts: {}, run_imme
     assignments_to_recompute = assignments || Assignment.active.where(context: course).pluck(:id)
     return if assignments_to_recompute.empty?
 
-    executing_user ||= self.current_executing_user
+    executing_user ||= current_executing_user
     due_date_cacher = new(course, assignments_to_recompute, update_grades: update_grades, original_caller: original_caller, executing_user: executing_user)
     if run_immediately
       due_date_cacher.recompute
@@ -133,7 +133,7 @@ def self.recompute_users_for_course(user_ids, course, assignments = nil, inst_jo
 
     current_caller = caller(1..1).first
     update_grades = inst_jobs_opts.delete(:update_grades) || false
-    executing_user = inst_jobs_opts.delete(:executing_user) || self.current_executing_user
+    executing_user = inst_jobs_opts.delete(:executing_user) || current_executing_user
     due_date_cacher = new(course, assignments, user_ids, update_grades: update_grades, original_caller: current_caller, executing_user: executing_user)
 
     due_date_cacher.delay_if_production(**inst_jobs_opts).recompute
diff --git a/lib/feature.rb b/lib/feature.rb
index 69048360e4076..d6950e49d0cc8 100644
--- a/lib/feature.rb
+++ b/lib/feature.rb
@@ -76,7 +76,7 @@ def self.environment
   end
 
   def self.production_environment?
-    self.environment == :production
+    environment == :production
   end
 
   # Register one or more features.  Must be done during application initialization.
@@ -171,7 +171,7 @@ def self.apply_environment_overrides!(feature_name, feature_hash)
     if environments
       raise "invalid environment tag for feature #{feature_name}: must be one of #{VALID_ENVS}" unless (environments.keys - VALID_ENVS).empty?
 
-      env = self.environment
+      env = environment
       if environments.key?(env)
         feature_hash.merge!(environments[env])
       end
@@ -248,7 +248,7 @@ def self.transitions(feature_name, user, context, orig_state)
   end
 
   def self.remove_obsolete_flags
-    valid_features = self.definitions.keys
+    valid_features = definitions.keys
     cutoff = Setting.get('obsolete_feature_flag_cutoff_days', 60).to_i.days.ago
     delete_scope = FeatureFlag.where('updated_at e
     Canvas::Errors.capture_exception(:gradebook_import, e, :info)
     # this isn't actually "retryable", but this error will make sure
@@ -300,7 +300,7 @@ def parse!
       end
     end
 
-    @upload.gradebook = self.as_json
+    @upload.gradebook = as_json
     @upload.save!
   end
 
diff --git a/lib/has_content_tags.rb b/lib/has_content_tags.rb
index 79d4509310ee4..8d71a71206a95 100644
--- a/lib/has_content_tags.rb
+++ b/lib/has_content_tags.rb
@@ -29,15 +29,15 @@ def update_associated_content_tags
 
   def check_if_associated_content_tags_need_updating
     @associated_content_tags_need_updating = false
-    return if self.new_record?
-    return if self.respond_to?(:context_type) && %w[SisBatch Folder].include?(self.context_type)
-
-    @associated_content_tags_need_updating = true if self.respond_to?(:title_changed?) && self.title_changed?
-    @associated_content_tags_need_updating = true if self.respond_to?(:name_changed?) && self.name_changed?
-    @associated_content_tags_need_updating = true if self.respond_to?(:display_name_changed?) && self.display_name_changed?
-    @associated_content_tags_need_updating = true if self.respond_to?(:points_possible_changed?) && self.points_possible_changed?
-    @associated_content_tags_need_updating = true if (self.respond_to?(:workflow_state_changed?) && self.workflow_state_changed?) || self.workflow_state == 'deleted'
-    @associated_content_tags_need_updating = true if self.is_a?(Attachment) && self.locked_changed?
+    return if new_record?
+    return if respond_to?(:context_type) && %w[SisBatch Folder].include?(context_type)
+
+    @associated_content_tags_need_updating = true if respond_to?(:title_changed?) && title_changed?
+    @associated_content_tags_need_updating = true if respond_to?(:name_changed?) && name_changed?
+    @associated_content_tags_need_updating = true if respond_to?(:display_name_changed?) && display_name_changed?
+    @associated_content_tags_need_updating = true if respond_to?(:points_possible_changed?) && points_possible_changed?
+    @associated_content_tags_need_updating = true if (respond_to?(:workflow_state_changed?) && workflow_state_changed?) || workflow_state == 'deleted'
+    @associated_content_tags_need_updating = true if is_a?(Attachment) && locked_changed?
   end
 
   def self.included(klass)
@@ -47,8 +47,8 @@ def self.included(klass)
 
   def locked_request_cache_key(user)
     keys = ['_locked_for4', self, user]
-    unlocked_at = self.respond_to?(:unlock_at) ? self.unlock_at : nil
-    locked_at = self.respond_to?(:lock_at) ? self.lock_at : nil
+    unlocked_at = respond_to?(:unlock_at) ? unlock_at : nil
+    locked_at = respond_to?(:lock_at) ? lock_at : nil
     keys << (unlocked_at ? unlocked_at > Time.zone.now : false)
     keys << (locked_at ? locked_at < Time.zone.now : false)
     keys
diff --git a/lib/inst_fs.rb b/lib/inst_fs.rb
index d27f65319b929..fe4cb377bb39c 100644
--- a/lib/inst_fs.rb
+++ b/lib/inst_fs.rb
@@ -61,7 +61,7 @@ def bearer_token(options)
         iat: Time.now.utc.to_i,
         user_id: options[:user]&.global_id&.to_s
       }
-      Canvas::Security.create_jwt(claims, expires_in.from_now, self.jwt_secret, :HS512)
+      Canvas::Security.create_jwt(claims, expires_in.from_now, jwt_secret, :HS512)
     end
 
     def authenticated_url(attachment, options = {})
@@ -329,7 +329,7 @@ def thumbnail_path(attachment)
     # `expires_at` can be either a Time or an ActiveSupport::Duration
     def service_jwt(claims, expires_at)
       expires_at = expires_at.from_now if expires_at.respond_to?(:from_now)
-      Canvas::Security.create_jwt(claims, expires_at, self.jwt_secret, :HS512)
+      Canvas::Security.create_jwt(claims, expires_at, jwt_secret, :HS512)
     end
 
     # floor_to rounds `number` down to a multiple of the chosen step.
diff --git a/lib/learning_outcome_context.rb b/lib/learning_outcome_context.rb
index f04145389373a..de91144d79cf7 100644
--- a/lib/learning_outcome_context.rb
+++ b/lib/learning_outcome_context.rb
@@ -82,7 +82,7 @@ def update_root_outcome_group_name
       return unless root
 
       self.class.connection.after_transaction_commit do
-        root.update! title: self.name
+        root.update! title: name
       end
     end
   end
diff --git a/lib/lti/app_launch_collator.rb b/lib/lti/app_launch_collator.rb
index 3367249b6dfac..4239391a0dd92 100644
--- a/lib/lti/app_launch_collator.rb
+++ b/lib/lti/app_launch_collator.rb
@@ -132,7 +132,7 @@ def lti2_launch_definition(message_handler, placements)
           name: message_handler.resource_handler.name,
           description: message_handler.resource_handler.description,
           domain: URI(message_handler.launch_path).host,
-          placements: self.lti2_placements(message_handler, placements)
+          placements: lti2_placements(message_handler, placements)
         }
       end
 
diff --git a/lib/lti/variable_expander.rb b/lib/lti/variable_expander.rb
index 5deca49be1480..0786d16709f24 100644
--- a/lib/lti/variable_expander.rb
+++ b/lib/lti/variable_expander.rb
@@ -52,11 +52,11 @@ def self.expansions
     end
 
     def self.expansion_keys
-      self.expansions.keys.map { |c| c.to_s[1..] }
+      expansions.keys.map { |c| c.to_s[1..] }
     end
 
     def self.default_name_expansions
-      self.expansions.values.select { |v| v.default_name.present? }.map(&:name)
+      expansions.values.select { |v| v.default_name.present? }.map(&:name)
     end
 
     def self.find_expansion(key)
@@ -64,11 +64,11 @@ def self.find_expansion(key)
 
       if (md = key.to_s.match(PARAMETERS_REGEX))
         real_key = md[1] + "<>"
-        if (expansion = self.expansions[real_key.to_sym])
+        if (expansion = expansions[real_key.to_sym])
           [expansion, md[2]]
         end
       else
-        self.expansions[key.to_sym]
+        expansions[key.to_sym]
       end
     end
 
diff --git a/lib/message_bus.rb b/lib/message_bus.rb
index 3ca3d7fcd8a68..342970b0cd6b4 100644
--- a/lib/message_bus.rb
+++ b/lib/message_bus.rb
@@ -128,9 +128,9 @@ def self.producer_for(namespace, topic_name, force_fresh: false)
     ns = MessageBus::Namespace.build(namespace)
     check_conn_pool(["producers", ns.to_s, topic_name], force_fresh: force_fresh) do
       Bundler.require(:pulsar)
-      ::MessageBus::CaCert.ensure_presence!(self.config)
-      topic = self.topic_url(ns, topic_name)
-      self.client.create_producer(topic)
+      ::MessageBus::CaCert.ensure_presence!(config)
+      topic = topic_url(ns, topic_name)
+      client.create_producer(topic)
     end
   end
 
@@ -171,18 +171,18 @@ def self.consumer_for(namespace, topic_name, subscription_name, force_fresh: fal
     ns = MessageBus::Namespace.build(namespace)
     check_conn_pool(["consumers", ns.to_s, topic_name, subscription_name], force_fresh: force_fresh) do
       Bundler.require(:pulsar)
-      ::MessageBus::CaCert.ensure_presence!(self.config)
+      ::MessageBus::CaCert.ensure_presence!(config)
       topic = topic_url(ns, topic_name)
       consumer_config = Pulsar::ConsumerConfiguration.new({})
       consumer_config.subscription_initial_position = :earliest
-      self.client.subscribe(topic, subscription_name, consumer_config)
+      client.subscribe(topic, subscription_name, consumer_config)
     end
   end
 
   def self.topic_url(namespace, topic_name, app_env = Canvas.environment)
     ns = MessageBus::Namespace.build(namespace)
     app_env = (app_env || "development").downcase
-    conf_hash = self.config
+    conf_hash = config
     # by using the application env in the topic name, we can
     # share a non-prod pulsar instance between environments
     # like test/beta/edge whatever and not have to provision
@@ -278,7 +278,7 @@ def self.client
     return @client if @client
 
     Bundler.require(:pulsar)
-    conf_hash = self.config
+    conf_hash = config
     token_vault_path = conf_hash['PULSAR_TOKEN_VAULT_PATH']
     if token_vault_path.present?
       conf_hash = conf_hash.dup
@@ -294,7 +294,7 @@ def self.client
   end
 
   def self.enabled?
-    hash = self.config
+    hash = config
     hash['PULSAR_BROKER_URI'].present? && hash['PULSAR_TENANT'].present?
   end
 
diff --git a/lib/message_bus/async_producer.rb b/lib/message_bus/async_producer.rb
index 997d8002a1911..fe4ce681a4ea4 100644
--- a/lib/message_bus/async_producer.rb
+++ b/lib/message_bus/async_producer.rb
@@ -45,7 +45,7 @@ def initialize(start_thread: true)
       @logger = MessageBus.logger
       @interval = MessageBus.worker_process_interval
 
-      self.start! if start_thread
+      start! if start_thread
     end
 
     def push(namespace, topic_name, message)
@@ -78,7 +78,7 @@ def stop!
     end
 
     def start!
-      @thread = Thread.new { self.run_thread }
+      @thread = Thread.new { run_thread }
     end
 
     def run_thread
diff --git a/lib/message_bus/ca_cert.rb b/lib/message_bus/ca_cert.rb
index 81d9361902b94..d587a46d28637 100644
--- a/lib/message_bus/ca_cert.rb
+++ b/lib/message_bus/ca_cert.rb
@@ -44,7 +44,7 @@ def self.ensure_presence!(config_hash)
 
       cert_vault_path = config_hash.fetch("PULSAR_CERT_VAULT_PATH")
       process_file_version = cert_path_on_disk.gsub(".pem", "-#{Process.pid}-#{Thread.current.object_id}.pem")
-      self.write_cert(cert_vault_path, process_file_version)
+      write_cert(cert_vault_path, process_file_version)
       # it's possible another process has already
       # moved this file into place, in which case do nothing.
       return true if File.exist?(cert_path_on_disk)
diff --git a/lib/message_bus/message_id.rb b/lib/message_bus/message_id.rb
index 7e81eb586d9d0..dac4905d14b2c 100644
--- a/lib/message_bus/message_id.rb
+++ b/lib/message_bus/message_id.rb
@@ -61,15 +61,15 @@ def self.from_hash(hash)
     end
 
     def <=>(other)
-      if !other.is_a?(::MessageBus::MessageId) || other.partition_id != self.partition_id
+      if !other.is_a?(::MessageBus::MessageId) || other.partition_id != partition_id
         raise ArgumentError, "MessageID can only compare to other message IDs in the same partition"
       end
 
-      return self.ledger_id <=> other.ledger_id unless other.ledger_id == self.ledger_id
+      return ledger_id <=> other.ledger_id unless other.ledger_id == ledger_id
 
-      return self.entry_id <=> other.entry_id unless other.entry_id == self.entry_id
+      return entry_id <=> other.entry_id unless other.entry_id == entry_id
 
-      self.batch_index <=> other.batch_index
+      batch_index <=> other.batch_index
     end
 
     def to_s
diff --git a/lib/message_bus/namespace.rb b/lib/message_bus/namespace.rb
index 5ba73bd5f1bf0..f63b15573d1e4 100644
--- a/lib/message_bus/namespace.rb
+++ b/lib/message_bus/namespace.rb
@@ -37,7 +37,7 @@ def initialize(namespace_base_string)
     def self.build(namespace)
       return namespace if namespace.is_a?(::MessageBus::Namespace)
 
-      self.new(namespace)
+      new(namespace)
     end
 
     # If somehow the consuming code is already injecting
diff --git a/lib/message_dispatcher.rb b/lib/message_dispatcher.rb
index d172c6901800f..b2162611c8f17 100644
--- a/lib/message_dispatcher.rb
+++ b/lib/message_dispatcher.rb
@@ -20,7 +20,7 @@
 
 class MessageDispatcher < Delayed::PerformableMethod
   def self.dispatch(message)
-    Delayed::Job.enqueue(self.new(message.for_queue, :deliver),
+    Delayed::Job.enqueue(new(message.for_queue, :deliver),
                          run_at: message.dispatch_at,
                          priority: 25,
                          max_attempts: 15)
@@ -30,11 +30,11 @@ def self.batch_dispatch(messages)
     return if messages.empty?
 
     if messages.size == 1
-      self.dispatch(messages.first)
+      dispatch(messages.first)
       return
     end
 
-    Delayed::Job.enqueue(self.new(self, :deliver_batch, args: [messages.map(&:for_queue)]),
+    Delayed::Job.enqueue(new(self, :deliver_batch, args: [messages.map(&:for_queue)]),
                          run_at: messages.first.dispatch_at,
                          priority: 25,
                          max_attempts: 15)
@@ -81,7 +81,7 @@ def self.deliver_batch(messages)
       message.deliver
     rescue
       # this delivery failed, we'll have to make an individual job to retry
-      self.dispatch(message)
+      dispatch(message)
     end
   end
 end
diff --git a/lib/messageable_user.rb b/lib/messageable_user.rb
index 422b6c94c462c..29c8544cd6c8c 100644
--- a/lib/messageable_user.rb
+++ b/lib/messageable_user.rb
@@ -146,8 +146,8 @@ def populate_common_contexts
   after_find :populate_common_contexts
 
   def include_common_contexts_from(other)
-    combine_common_contexts(self.global_common_courses, other.global_common_courses)
-    combine_common_contexts(self.global_common_groups, other.global_common_groups)
+    combine_common_contexts(global_common_courses, other.global_common_courses)
+    combine_common_contexts(global_common_groups, other.global_common_groups)
   end
 
   def serializable_hash(options = {})
diff --git a/lib/microsoft_sync/state_machine_job.rb b/lib/microsoft_sync/state_machine_job.rb
index db6da31ecf1e9..ceb54ca37e26a 100644
--- a/lib/microsoft_sync/state_machine_job.rb
+++ b/lib/microsoft_sync/state_machine_job.rb
@@ -245,8 +245,8 @@ def run(step, initial_mem_state, synchronous = false)
           raise InternalError, 'A job is waiting to be retried; use run_later() to enqueue another'
         end
 
-        self.delay(strand: strand, run_at: currently_retrying_job.run_at + 1)
-            .run(nil, initial_mem_state)
+        delay(strand: strand, run_at: currently_retrying_job.run_at + 1)
+          .run(nil, initial_mem_state)
       end
     end
 
@@ -321,8 +321,8 @@ def run_with_delay(step: nil, delay_amount: nil, initial_mem_state: nil, synchro
         return
       end
 
-      self.delay(strand: strand, run_at: delay_amount&.seconds&.from_now)
-          .run(step, initial_mem_state)
+      delay(strand: strand, run_at: delay_amount&.seconds&.from_now)
+        .run(step, initial_mem_state)
     end
 
     def update_state_record_to_errored_and_cleanup(error, capture: nil)
diff --git a/lib/mutable.rb b/lib/mutable.rb
index bc7875ffb698e..e2131a524ee4e 100644
--- a/lib/mutable.rb
+++ b/lib/mutable.rb
@@ -21,7 +21,7 @@ module Mutable
   def mute!
     return if muted?
 
-    self.update_attribute(:muted, true)
+    update_attribute(:muted, true)
     clear_sent_messages
     hide_submissions if respond_to?(:hide_submissions)
     ensure_post_policy(post_manually: true) if respond_to?(:ensure_post_policy)
@@ -31,7 +31,7 @@ def mute!
   def unmute!
     return unless muted?
 
-    self.update_attribute(:muted, false)
+    update_attribute(:muted, false)
     post_submissions if respond_to?(:post_submissions)
     ensure_post_policy(post_manually: false) if respond_to?(:ensure_post_policy)
     true
@@ -40,7 +40,7 @@ def unmute!
   protected
 
   def clear_sent_messages
-    self.clear_broadcast_messages if self.respond_to? :clear_broadcast_messages
+    clear_broadcast_messages if respond_to? :clear_broadcast_messages
   end
 
   def hide_stream_items(submissions:)
@@ -60,7 +60,7 @@ def hide_stream_items(submissions:)
 
       # Teachers want to hide their submission comments if they mute
       # the assignment after leaving them.
-      instructor_ids = self.context.instructors.pluck(:id)
+      instructor_ids = context.instructors.pluck(:id)
       visible_comment_sub_ids =
         SubmissionComment.where(hidden: false, submission_id: submission_ids, author_id: instructor_ids)
                          .pluck(:submission_id)
diff --git a/lib/open_object.rb b/lib/open_object.rb
index 7b8f24cb86ae7..be5d5da54dd51 100644
--- a/lib/open_object.rb
+++ b/lib/open_object.rb
@@ -36,14 +36,14 @@ def self.build(type, data = {})
   end
 
   def id
-    self.table[:id]
+    table[:id]
   end
 
   def asset_string
-    return self.table[:asset_string] if self.table[:asset_string]
-    return nil unless self.type && self.id
+    return table[:asset_string] if table[:asset_string]
+    return nil unless type && id
 
-    "#{self.type.underscore}_#{self.id}"
+    "#{type.underscore}_#{id}"
   end
 
   def as_json(options = {})
diff --git a/lib/plannable.rb b/lib/plannable.rb
index 63ec82e272b8b..864002528c25c 100644
--- a/lib/plannable.rb
+++ b/lib/plannable.rb
@@ -40,22 +40,22 @@ def update_associated_planner_overrides
 
   def check_if_associated_planner_overrides_need_updating
     @associated_planner_items_need_updating = false
-    return if self.new_record?
-    return if self.respond_to?(:context_type) && !PlannerOverride::CONTENT_TYPES.include?(self.context_type)
+    return if new_record?
+    return if respond_to?(:context_type) && !PlannerOverride::CONTENT_TYPES.include?(context_type)
 
-    @associated_planner_items_need_updating = true if self.try(:workflow_state_changed?) || self.workflow_state == 'deleted'
+    @associated_planner_items_need_updating = true if try(:workflow_state_changed?) || workflow_state == 'deleted'
   end
 
   def planner_override_for(user)
-    if self.respond_to? :submittable_object
-      submittable_override = self.submittable_object&.planner_override_for(user)
+    if respond_to? :submittable_object
+      submittable_override = submittable_object&.planner_override_for(user)
       return submittable_override if submittable_override
     end
 
-    if self.association(:planner_overrides).loaded?
-      self.planner_overrides.find { |po| po.user_id == user.id && po.workflow_state != 'deleted' }
+    if association(:planner_overrides).loaded?
+      planner_overrides.find { |po| po.user_id == user.id && po.workflow_state != 'deleted' }
     else
-      self.planner_overrides.where(user_id: user).where.not(workflow_state: 'deleted').take
+      planner_overrides.where(user_id: user).where.not(workflow_state: 'deleted').take
     end
   end
 
diff --git a/lib/request_error.rb b/lib/request_error.rb
index 19ff2d2167abd..90c04997dc57f 100644
--- a/lib/request_error.rb
+++ b/lib/request_error.rb
@@ -27,8 +27,8 @@ def initialize(message, status = :bad_request)
 
   def error_json
     {
-      status: (Rack::Utils::SYMBOL_TO_STATUS_CODE.key(self.response_status) || :internal_server_error).to_s,
-      message: self.message
+      status: (Rack::Utils::SYMBOL_TO_STATUS_CODE.key(response_status) || :internal_server_error).to_s,
+      message: message
     }
   end
 end
diff --git a/lib/schemas/base.rb b/lib/schemas/base.rb
index 0ea8f008f56b3..577bddab0b818 100644
--- a/lib/schemas/base.rb
+++ b/lib/schemas/base.rb
@@ -23,7 +23,7 @@ class Base
     delegate :validate, :valid?, to: :schema_checker
 
     def self.simple_validation_errors(json_hash)
-      error = self.new.validate(json_hash).to_a.first
+      error = new.validate(json_hash).to_a.first
       return nil if error.blank?
       if error['data_pointer'].present?
         return "#{error['data']} #{error['data_pointer']}. Schema: #{error['schema']}"
diff --git a/lib/score_statistics_generator.rb b/lib/score_statistics_generator.rb
index 4d3c5ac88efca..8d43431c3e012 100644
--- a/lib/score_statistics_generator.rb
+++ b/lib/score_statistics_generator.rb
@@ -37,8 +37,8 @@ def self.update_score_statistics_in_singleton(course_id)
   def self.update_score_statistics(course_id)
     root_account_id = Course.find_by(id: course_id)&.root_account_id
 
-    self.update_assignment_score_statistics(course_id, root_account_id: root_account_id)
-    self.update_course_score_statistic(course_id)
+    update_assignment_score_statistics(course_id, root_account_id: root_account_id)
+    update_course_score_statistic(course_id)
   end
 
   def self.update_assignment_score_statistics(course_id, root_account_id:)
diff --git a/lib/search_term_helper.rb b/lib/search_term_helper.rb
index 84db34a31d568..c5588250d6847 100644
--- a/lib/search_term_helper.rb
+++ b/lib/search_term_helper.rb
@@ -25,7 +25,7 @@ def search_by_attribute(scope, attr, search_term)
       if search_term.present?
         SearchTermHelper.validate_search_term(search_term)
         scope = if scope.respond_to?(:where)
-                  scope.where(wildcard("#{self.table_name}.#{attr}", search_term))
+                  scope.where(wildcard("#{table_name}.#{attr}", search_term))
                 else
                   scope.select { |item| item.matches_attribute?(attr, search_term) }
                 end
diff --git a/lib/send_to_stream.rb b/lib/send_to_stream.rb
index f4650ac1c1507..d240f3b9d33a1 100644
--- a/lib/send_to_stream.rb
+++ b/lib/send_to_stream.rb
@@ -44,7 +44,7 @@ def on_update_send_to_streams(&block)
   module SendToStreamInstanceMethods
     def queue_create_stream_items
       block = self.class.send_to_stream_block rescue nil
-      stream_recipients = Array(self.instance_eval(&block)) if block
+      stream_recipients = Array(instance_eval(&block)) if block
       if stream_recipients && !stream_recipients.empty?
         delay_if_production(priority: Delayed::LOW_PRIORITY).create_stream_items
       end
@@ -55,7 +55,7 @@ def create_stream_items
       return if stream_item_inactive?
 
       block = self.class.send_to_stream_block
-      stream_recipients = Array(self.instance_eval(&block)) if block
+      stream_recipients = Array(instance_eval(&block)) if block
       generate_stream_items(stream_recipients) if stream_recipients
     rescue => e
       if Rails.env.production?
@@ -67,14 +67,14 @@ def create_stream_items
 
     def generate_stream_items(stream_recipients)
       @generated_stream_items ||= []
-      self.extend TextHelper
+      extend TextHelper
       @stream_item_recipient_ids = stream_recipients.compact.filter_map { |u| User.infer_id(u) }.uniq
       @generated_stream_items = StreamItem.generate_all(self, @stream_item_recipient_ids)
     end
 
     def queue_update_stream_items
       block = self.class.send_to_stream_update_block
-      stream_recipients = Array(self.instance_eval(&block)) if block
+      stream_recipients = Array(instance_eval(&block)) if block
       if stream_recipients && !stream_recipients.empty?
         delay_if_production(priority: 25).generate_stream_items(stream_recipients)
         true
@@ -87,7 +87,7 @@ def queue_update_stream_items
     attr_reader :generated_stream_items, :stream_item_recipient_ids
 
     def stream_item_inactive?
-      (self.respond_to?(:workflow_state) && self.workflow_state == 'deleted') || (self.respond_to?(:deleted?) && self.deleted?)
+      (respond_to?(:workflow_state) && workflow_state == 'deleted') || (respond_to?(:deleted?) && deleted?)
     end
 
     def clear_stream_items_on_destroy
@@ -97,7 +97,7 @@ def clear_stream_items_on_destroy
     def clear_stream_items
       # We need to pass the asset_string, not the asset itself, since we're about to delete the asset
       root_object = StreamItem.root_object(self)
-      StreamItem.delay_if_production.delete_all_for([root_object.class.base_class.name, root_object.id], [self.class.base_class.name, self.id])
+      StreamItem.delay_if_production.delete_all_for([root_object.class.base_class.name, root_object.id], [self.class.base_class.name, id])
     end
   end
 
diff --git a/lib/sentry_proxy.rb b/lib/sentry_proxy.rb
index 4b900b70deb40..722bc0afe4f6d 100644
--- a/lib/sentry_proxy.rb
+++ b/lib/sentry_proxy.rb
@@ -34,7 +34,7 @@ def self.capture(exception, data, level = :error)
   #  configure the sentry client in an initializer).  This allows plugins and extensions
   # to register their own errors that they don't want to get reported to sentry
   def self.register_ignorable_error(error_class)
-    @ignorable_errors = (self.ignorable_errors << error_class.to_s).uniq
+    @ignorable_errors = (ignorable_errors << error_class.to_s).uniq
   end
 
   def self.ignorable_errors
diff --git a/lib/sis/account_importer.rb b/lib/sis/account_importer.rb
index 4f0ce0819cede..1af4e9ef4d06b 100644
--- a/lib/sis/account_importer.rb
+++ b/lib/sis/account_importer.rb
@@ -97,7 +97,7 @@ def add_account(account_id, parent_account_id, status, name, integration_id)
 
         unless account.changed?
           @success_count += 1
-          self.accounts_to_set_sis_batch_ids << account.id unless account.sis_batch_id == @batch.try(:id)
+          accounts_to_set_sis_batch_ids << account.id unless account.sis_batch_id == @batch.try(:id)
           return
         end
 
diff --git a/lib/sis/csv/import_refactored.rb b/lib/sis/csv/import_refactored.rb
index 031cd2192826f..596c1e819cc4e 100644
--- a/lib/sis/csv/import_refactored.rb
+++ b/lib/sis/csv/import_refactored.rb
@@ -81,7 +81,7 @@ def initialize(root_account, opts = {})
       end
 
       def self.process(root_account, opts = {})
-        importer = self.new(root_account, opts)
+        importer = new(root_account, opts)
         importer.process
         importer
       end
diff --git a/lib/sorts_assignments.rb b/lib/sorts_assignments.rb
index 3e4eddb007ab4..845df92b3678c 100644
--- a/lib/sorts_assignments.rb
+++ b/lib/sorts_assignments.rb
@@ -127,7 +127,7 @@ def bucket_filter(given_scope, bucket, session, user, current_user, context, sub
                            user
                          end
 
-      sorted_assignments = self.by_due_date(
+      sorted_assignments = by_due_date(
         :course => context,
         :assignments => overridden_assignments,
         :user => user_for_sorting,
diff --git a/lib/ssl_common.rb b/lib/ssl_common.rb
index 2ca8aadd897ba..ff3507445b1b3 100644
--- a/lib/ssl_common.rb
+++ b/lib/ssl_common.rb
@@ -36,7 +36,7 @@ def get_http_conn(host, port, ssl)
 
     def raw_post(url, payload, headers = {}, form_data = nil)
       url = URI.parse(url)
-      http = self.get_http_conn(url.host, url.port, url.scheme.casecmp?('https'))
+      http = get_http_conn(url.host, url.port, url.scheme.casecmp?('https'))
       req = Net::HTTP::Post.new(url.request_uri, headers)
       req.basic_auth URI.unescape(url.user || ""), URI.unescape(url.password || "") if url.user
       req.form_data = form_data if form_data
@@ -45,21 +45,21 @@ def raw_post(url, payload, headers = {}, form_data = nil)
 
     def get(url, headers = {})
       url = URI.parse(url)
-      http = self.get_http_conn(url.host, url.port, url.scheme.casecmp?('https'))
+      http = get_http_conn(url.host, url.port, url.scheme.casecmp?('https'))
       http.get(url.request_uri, headers)
     end
 
     def post_form(url, form_data, headers = {})
-      self.raw_post(url, nil, headers, form_data)
+      raw_post(url, nil, headers, form_data)
     end
 
     def post_multipart_form(url, form_data, headers = {}, field_priority = [])
       payload, mp_headers = Multipart::Post.new.prepare_query(form_data, field_priority)
-      self.raw_post(url, payload, mp_headers.merge(headers))
+      raw_post(url, payload, mp_headers.merge(headers))
     end
 
     def post_data(url, data, content_type, headers = {})
-      self.raw_post(url, data, { "Content-Type" => content_type }.merge(headers))
+      raw_post(url, data, { "Content-Type" => content_type }.merge(headers))
     end
   end
 end
diff --git a/lib/sticky_sis_fields.rb b/lib/sticky_sis_fields.rb
index 45ccc6de29c3b..a91a60f15f412 100644
--- a/lib/sticky_sis_fields.rb
+++ b/lib/sticky_sis_fields.rb
@@ -86,7 +86,7 @@ def load_stuck_sis_fields_cache
     def calculate_currently_stuck_sis_fields
       @sis_fields_to_stick ||= [].to_set
       @sis_fields_to_unstick ||= [].to_set
-      changed_sis_fields = self.class.sticky_sis_fields & (self.changed.map(&:to_sym).to_set | @sis_fields_to_stick)
+      changed_sis_fields = self.class.sticky_sis_fields & (changed.map(&:to_sym).to_set | @sis_fields_to_stick)
       (load_stuck_sis_fields_cache | changed_sis_fields) - @sis_fields_to_unstick
     end
   end
@@ -119,7 +119,7 @@ def process_as_sis(opts = {}, &block)
         if opts[:add_sis_stickiness] || opts[:clear_sis_stickiness]
           yield
         else
-          self.suspend_callbacks(:set_sis_stickiness, &block)
+          suspend_callbacks(:set_sis_stickiness, &block)
         end
       ensure
         self.sis_stickiness_options = old_options
diff --git a/lib/submission_list.rb b/lib/submission_list.rb
index d51971f61e4c0..dbb117fb19c59 100644
--- a/lib/submission_list.rb
+++ b/lib/submission_list.rb
@@ -104,12 +104,12 @@ def initialize(course)
 
   # An iterator on a sorted and filtered list of submission versions.
   def each(&block)
-    self.submission_entries.each(&block)
+    submission_entries.each(&block)
   end
 
   # An iterator on the day only, not each submission
   def each_day(&block)
-    self.list.each(&block)
+    list.each(&block)
   end
 
   # An array of days with an array of grader open structs for that day and course.
@@ -120,7 +120,7 @@ def days
     # puts "----------------------------------------------"
     # puts "starting"
     # puts "---------------------------------------------------------------------------------"
-    self.list.map do |day, _value|
+    list.map do |day, _value|
       # puts "-----------------------------------------------item #{Time.now - current}----------------------------"
       # current = Time.now
       OpenObject.new(:date => day, :graders => graders_for_day(day))
@@ -149,14 +149,14 @@ def submission_entries
 
   # A cleaner look at a SubmissionList
   def inspect
-    "SubmissionList: course: #{self.course.name} submissions used: #{self.submission_entries.size} days used: #{self.list.keys.inspect} graders: #{self.graders.map(&:name).inspect}"
+    "SubmissionList: course: #{course.name} submissions used: #{submission_entries.size} days used: #{list.keys.inspect} graders: #{graders.map(&:name).inspect}"
   end
 
   protected
 
   # Returns an array of graders with an array of assignment open structs
   def graders_for_day(day)
-    hsh = self.list[day].each_with_object({}) do |submission, h|
+    hsh = list[day].each_with_object({}) do |submission, h|
       grader = submission[:grader]
       h[grader] ||= OpenObject.new(
         :assignments => assignments_for_grader_and_day(grader, day),
@@ -191,8 +191,8 @@ def assignments_for_grader_and_day(grader, day)
   # Produce @list, wich is a sorted, filtered, list of submissions with
   # all the meta data we need and no banned keys included.
   def process
-    @list = self.submission_entries.sort_by { |a| [a[:graded_at] ? -a[:graded_at].to_f : CanvasSort::Last, a[:safe_grader_id], a[:assignment_id]] }
-                .each_with_object(Hashery::Dictionary.new) do |se, d|
+    @list = submission_entries.sort_by { |a| [a[:graded_at] ? -a[:graded_at].to_f : CanvasSort::Last, a[:safe_grader_id], a[:assignment_id]] }
+                              .each_with_object(Hashery::Dictionary.new) do |se, d|
       d[se[:graded_on]] ||= []
       d[se[:graded_on]] << se
     end
@@ -200,9 +200,9 @@ def process
 
   # A hash of the current grades of each submission, keyed by submission.id
   def current_grade_map
-    @current_grade_map ||= self.course.submissions.not_placeholder.each_with_object({}) do |submission, hash|
+    @current_grade_map ||= course.submissions.not_placeholder.each_with_object({}) do |submission, hash|
       grader = if submission.grader_id.present?
-                 self.grader_map[submission.grader_id].try(:name)
+                 grader_map[submission.grader_id].try(:name)
                end
       grader ||= I18n.t('gradebooks.history.graded_on_submission', 'Graded on submission')
 
@@ -291,7 +291,7 @@ def translate_score(submission)
 
   # A list of all versions in YAML format
   def yaml_list
-    @yaml_list ||= self.course.submissions.not_placeholder.preload(:versions).map do |s|
+    @yaml_list ||= course.submissions.not_placeholder.preload(:versions).map do |s|
       s.versions.map(&:yaml)
     end.flatten
   end
@@ -323,7 +323,7 @@ def add_regrade_info(hash_list)
 
   # Still a list of unsorted, unfiltered hashes, but the meta data is inserted at this point
   def full_hash_list
-    @full_hash_list ||= self.raw_hash_list.map do |h|
+    @full_hash_list ||= raw_hash_list.map do |h|
       h[:grader] = if h.key? :score_before_regrade
                      I18n.t('gradebooks.history.regraded', "Regraded")
                    elsif h[:grader_id] && grader_map[h[:grader_id]]
@@ -332,10 +332,10 @@ def full_hash_list
                      I18n.t('gradebooks.history.graded_on_submission', 'Graded on submission')
                    end
       h[:safe_grader_id] = h[:grader_id] || 0
-      h[:assignment_name] = self.assignment_map[h[:assignment_id]].title
+      h[:assignment_name] = assignment_map[h[:assignment_id]].title
       h[:student_user_id] = h[:user_id]
-      h[:student_name] = self.student_map[h[:user_id]].name
-      h[:course_id] = self.course.id
+      h[:student_name] = student_map[h[:user_id]].name
+      h[:course_id] = course.id
       h[:submission_id] = h[:id]
       h[:graded_on] = h[:graded_at].in_time_zone.to_date if h[:graded_at]
 
diff --git a/lib/submittable.rb b/lib/submittable.rb
index 13d2ce9ab61d4..9982c4f7bafcf 100644
--- a/lib/submittable.rb
+++ b/lib/submittable.rb
@@ -48,9 +48,9 @@ def visible_ids_by_user(opts)
       # section-specific discussions, so here get the ones visible to everyone in the
       # course, and below get the ones that are visible to the right section.
       ids_visible_to_all = if opts[:item_type] == :discussion
-                             self.without_assignment_in_course(opts[:course_id]).where(:is_section_specific => false).pluck(:id)
+                             without_assignment_in_course(opts[:course_id]).where(:is_section_specific => false).pluck(:id)
                            else
-                             self.without_assignment_in_course(opts[:course_id]).pluck(:id)
+                             without_assignment_in_course(opts[:course_id]).pluck(:id)
                            end
 
       # Now get the section-specific discussions that are in the proper sections.
@@ -72,74 +72,74 @@ def visible_ids_by_user(opts)
 
     def pluck_visibilities(opts)
       name = self.name.underscore.pluralize
-      self.joins_assignment_student_visibilities(opts[:user_id], opts[:course_id])
-          .pluck("#{name}.id", "#{name}.assignment_id", "assignment_student_visibilities.user_id")
+      joins_assignment_student_visibilities(opts[:user_id], opts[:course_id])
+        .pluck("#{name}.id", "#{name}.assignment_id", "assignment_student_visibilities.user_id")
     end
   end
 
   def sync_assignment
-    if (a = self.assignment)
-      a.title = self.title
+    if (a = assignment)
+      a.title = title
       name = self.class.name.underscore
       a.submission_types = name
       a.saved_by = name.to_sym
-      a.workflow_state = self.published? ? "published" : "unpublished"
+      a.workflow_state = published? ? "published" : "unpublished"
     end
   end
 
   def for_assignment?
     name = self.class.name.underscore
-    self.assignment && self.assignment.submission_types =~ /#{name}/
+    assignment && assignment.submission_types =~ /#{name}/
   end
 
   def restore(from = nil)
     self.workflow_state = 'unpublished'
-    self.save
+    save
 
-    if from != :assignment && self.for_assignment? && self.assignment.deleted?
+    if from != :assignment && for_assignment? && assignment.deleted?
       name = self.class.name.underscore
-      self.assignment.restore(name.to_sym)
+      assignment.restore(name.to_sym)
     end
   end
 
   def unlink!(type)
     @saved_by = type
     self.assignment = nil
-    self.destroy
+    destroy
   end
 
   def restore_old_assignment
-    return nil unless self.old_assignment&.deleted?
+    return nil unless old_assignment&.deleted?
 
-    self.old_assignment.workflow_state = 'published'
+    old_assignment.workflow_state = 'published'
     name = self.class.name.underscore
-    self.old_assignment.saved_by = name.to_sym
-    self.old_assignment.save(:validate => false)
-    self.old_assignment
+    old_assignment.saved_by = name.to_sym
+    old_assignment.save(:validate => false)
+    old_assignment
   end
 
   def update_assignment
-    if self.deleted?
-      if self.for_assignment? && !self.assignment.deleted?
+    if deleted?
+      if for_assignment? && !assignment.deleted?
         self.class.connection.after_transaction_commit do
-          self.assignment.destroy
+          assignment.destroy
         end
       end
     else
-      if !self.assignment_id && @old_assignment_id
-        self.context_module_tags.each(&:confirm_valid_module_requirements)
+      if !assignment_id && @old_assignment_id
+        context_module_tags.each(&:confirm_valid_module_requirements)
       end
       if @old_assignment_id
         Assignment.where(
           id: @old_assignment_id,
-          context: self.context,
+          context: context,
           submission_types: 'wiki_page'
         ).update_all(workflow_state: 'deleted', updated_at: Time.now.utc)
-      elsif self.assignment && @saved_by != :assignment
+      elsif assignment && @saved_by != :assignment
         # let the stack unwind before we sync this, so that we're not nesting callbacks
         self.class.connection.after_transaction_commit do
-          self.sync_assignment
-          self.assignment.save
+          sync_assignment
+          assignment.save
         end
       end
     end
@@ -147,14 +147,14 @@ def update_assignment
   protected :update_assignment
 
   def default_submission_values
-    if self.assignment_id != self.assignment_id_was
-      @old_assignment_id = self.assignment_id_was
+    if assignment_id != assignment_id_was
+      @old_assignment_id = assignment_id_was
     end
-    if self.assignment_id
-      self.assignment_id = nil unless (self.assignment &&
-                                      self.assignment.context == self.context) ||
-                                      self.try(:root_topic).try(:assignment_id) == self.assignment_id
-      self.old_assignment_id = self.assignment_id if self.assignment_id
+    if assignment_id
+      self.assignment_id = nil unless (assignment &&
+                                      assignment.context == context) ||
+                                      try(:root_topic).try(:assignment_id) == assignment_id
+      self.old_assignment_id = assignment_id if assignment_id
     end
   end
   protected :default_submission_values
diff --git a/lib/unzip_attachment.rb b/lib/unzip_attachment.rb
index 644dcdfcbc082..ab55e219acfb1 100644
--- a/lib/unzip_attachment.rb
+++ b/lib/unzip_attachment.rb
@@ -34,11 +34,11 @@ def self.process(opts = {})
 
   # for backwards compatibility
   def course
-    self.context
+    context
   end
 
   def course_files_folder
-    self.context_files_folder
+    context_files_folder
   end
 
   def initialize(opts = {})
@@ -53,9 +53,9 @@ def initialize(opts = {})
     @rename_files = !!opts[:rename_files]
     @migration_id_map = opts[:migration_id_map] || {}
 
-    raise ArgumentError, "Must provide a context." unless self.context&.is_a_context?
-    raise ArgumentError, "Must provide a filename." unless self.filename
-    raise ArgumentError, "Must provide a context files folder." unless self.context_files_folder
+    raise ArgumentError, "Must provide a context." unless context&.is_a_context?
+    raise ArgumentError, "Must provide a filename." unless filename
+    raise ArgumentError, "Must provide a context files folder." unless context_files_folder
   end
 
   def update_progress(pct)
@@ -96,7 +96,7 @@ def process
 
       id_positions = {}
       path_positions = zip_stats.paths_with_positions(last_position)
-      CanvasUnzip.extract_archive(self.filename) do |entry, index|
+      CanvasUnzip.extract_archive(filename) do |entry, index|
         next if should_skip?(entry)
 
         folder_path_array = path_elements_for(@context_files_folder.full_name)
@@ -151,11 +151,11 @@ def update_attachment_positions(id_positions)
   end
 
   def attach(path, entry, folder, md5, migration_id: nil)
-    FileInContext.attach(self.context, path, display_name: display_name(entry.name), folder: folder,
-                                             explicit_filename: File.split(entry.name).last, allow_rename: @rename_files, md5: md5, migration_id: migration_id)
+    FileInContext.attach(context, path, display_name: display_name(entry.name), folder: folder,
+                                        explicit_filename: File.split(entry.name).last, allow_rename: @rename_files, md5: md5, migration_id: migration_id)
   rescue
-    FileInContext.attach(self.context, path, display_name: display_name(entry.name), folder: folder,
-                                             explicit_filename: File.split(entry.name).last, allow_rename: @rename_files, md5: md5, migration_id: migration_id)
+    FileInContext.attach(context, path, display_name: display_name(entry.name), folder: folder,
+                                        explicit_filename: File.split(entry.name).last, allow_rename: @rename_files, md5: md5, migration_id: migration_id)
   end
 
   def with_unzip_configuration
@@ -215,7 +215,7 @@ def infer_folder(path)
   # Actually creates the folder in the database.
   def assert_folder(root, dir)
     folder = Folder.new(:parent_folder_id => root.id, :name => dir)
-    folder.context = self.context
+    folder.context = context
     folder.save!
     folder
   end
@@ -226,7 +226,7 @@ def folders(reset = false)
     @folders = nil if reset
     return @folders if @folders
 
-    @folders = OpenStruct.new(:root_directory => self.context_files_folder)
+    @folders = OpenStruct.new(:root_directory => context_files_folder)
   end
 end
 
diff --git a/lib/visibility_plucking_helper.rb b/lib/visibility_plucking_helper.rb
index 08c0df9b49dcd..13a418eebdf27 100644
--- a/lib/visibility_plucking_helper.rb
+++ b/lib/visibility_plucking_helper.rb
@@ -59,7 +59,7 @@ def check_args(opts, key)
     end
 
     def pluck_own_and_user_ids(column_to_pluck, opts)
-      self.where(opts).pluck(:user_id, column_to_pluck)
+      where(opts).pluck(:user_id, column_to_pluck)
     end
   end
 end
diff --git a/lib/zip_extractor.rb b/lib/zip_extractor.rb
index ec2e1f014c404..e76f16cbea503 100644
--- a/lib/zip_extractor.rb
+++ b/lib/zip_extractor.rb
@@ -52,10 +52,10 @@ def unzip_files(&block)
 
       local_name = File.join(dirname, File.split(zip_entry.name).last)
       zip_entry.extract(local_name)
-      self.unzipped_files << local_name
+      unzipped_files << local_name
     end
-    block&.call(self.unzipped_files)
-    self.unzipped_files
+    block&.call(unzipped_files)
+    unzipped_files
   end
 
   def remove_extracted_files!
diff --git a/spec/apis/api_spec_helper.rb b/spec/apis/api_spec_helper.rb
index ff3c914b036da..a578b4f856b79 100644
--- a/spec/apis/api_spec_helper.rb
+++ b/spec/apis/api_spec_helper.rb
@@ -22,7 +22,7 @@
 
 class HashWithDupCheck < Hash
   def []=(k, v)
-    if self.key?(k)
+    if key?(k)
       raise ArgumentError, "key already exists: #{k.inspect}"
     else
       super
diff --git a/spec/apis/general_api_spec.rb b/spec/apis/general_api_spec.rb
index d976d2a588852..9c78e3b7cb1a4 100644
--- a/spec/apis/general_api_spec.rb
+++ b/spec/apis/general_api_spec.rb
@@ -43,7 +43,7 @@
       course_with_teacher
       @course.send(:extend, RSpec::Matchers)
       def @course.filter_attributes_for_user(hash, user, session)
-        expect(user).to eq self.teachers.first
+        expect(user).to eq teachers.first
         expect(session).to be_nil
         hash.delete('sis_source_id')
       end
diff --git a/spec/apis/v1/discussion_topics_api_spec.rb b/spec/apis/v1/discussion_topics_api_spec.rb
index e28528979e567..5c7f340be34b7 100644
--- a/spec/apis/v1/discussion_topics_api_spec.rb
+++ b/spec/apis/v1/discussion_topics_api_spec.rb
@@ -1437,7 +1437,7 @@ def calls_display_topic(topic, opts = { except: [] })
 
       calls = [:get_show, :get_entries, :get_replies, :add_entry, :add_reply]
       calls.reject! { |call| opts[:except].include?(call) }
-      calls.each { |call| expect(self.send(call, topic).to_s).not_to eq "401" }
+      calls.each { |call| expect(send(call, topic).to_s).not_to eq "401" }
     end
 
     def calls_do_not_show_topic(topic)
@@ -1445,7 +1445,7 @@ def calls_do_not_show_topic(topic)
       expect(JSON.parse(response.body).to_s).not_to include(topic.assignment.title.to_s)
 
       calls = [:get_show, :get_entries, :get_replies, :add_entry, :add_reply]
-      calls.each { |call| expect(self.send(call, topic).to_s).to eq "401" }
+      calls.each { |call| expect(send(call, topic).to_s).to eq "401" }
     end
 
     def get_index(course)
diff --git a/spec/apis/v1/pages_api_spec.rb b/spec/apis/v1/pages_api_spec.rb
index 2e7dbf6c2ad84..8dfb8821e36dc 100644
--- a/spec/apis/v1/pages_api_spec.rb
+++ b/spec/apis/v1/pages_api_spec.rb
@@ -1550,14 +1550,14 @@ def calls_succeed(page, opts = { except: [] })
       expect(JSON.parse(response.body).to_s).to include(page.title)
 
       calls.reject! { |call| opts[:except].include?(call) }
-      calls.each { |call| expect(self.send(call, page).to_s).to eq "200" }
+      calls.each { |call| expect(send(call, page).to_s).to eq "200" }
     end
 
     def calls_fail(page)
       get_index
       expect(JSON.parse(response.body).to_s).not_to include(page.title.to_s)
 
-      calls.each { |call| expect(self.send(call, page).to_s).to eq "401" }
+      calls.each { |call| expect(send(call, page).to_s).to eq "401" }
     end
 
     before :once do
diff --git a/spec/apis/v1/submissions_api_spec.rb b/spec/apis/v1/submissions_api_spec.rb
index 7975999ee09df..be9def5aad08c 100644
--- a/spec/apis/v1/submissions_api_spec.rb
+++ b/spec/apis/v1/submissions_api_spec.rb
@@ -2014,7 +2014,7 @@ def call_to_for_students(opts = {})
                               { :controller => 'submissions_api', :action => 'for_students',
                                 :format => 'json', :course_id => @course.to_param },
                               { :student_ids => [@student.to_param] }]
-      self.send(*args)
+      send(*args)
     end
 
     context "as student" do
@@ -2271,7 +2271,7 @@ def call_to_submissions_show(opts = {})
                                 { :controller => 'submissions_api', :action => 'show',
                                   :format => 'json', :course_id => @course.to_param, :assignment_id => @assignment.id.to_s, :user_id => @student.id.to_s },
                                 { :include => includes }]
-        self.send(*args)
+        send(*args)
       end
 
       context "as teacher" do
diff --git a/spec/contracts/service_consumers/api/provider_states_for_consumer.rb b/spec/contracts/service_consumers/api/provider_states_for_consumer.rb
index b1bbb3f6be21d..03c3695493e3b 100644
--- a/spec/contracts/service_consumers/api/provider_states_for_consumer.rb
+++ b/spec/contracts/service_consumers/api/provider_states_for_consumer.rb
@@ -87,7 +87,7 @@ class BaseState
     )
 
     def self.seed!(opts: {})
-      self.new(opts)
+      new(opts)
     end
 
     private
diff --git a/spec/contracts/service_consumers/api/provider_states_for_consumer/oauth_provider_states.rb b/spec/contracts/service_consumers/api/provider_states_for_consumer/oauth_provider_states.rb
index e37be8240ee07..096817a6b2a41 100644
--- a/spec/contracts/service_consumers/api/provider_states_for_consumer/oauth_provider_states.rb
+++ b/spec/contracts/service_consumers/api/provider_states_for_consumer/oauth_provider_states.rb
@@ -171,7 +171,7 @@ def self.create_external_tool(developer_key)
 
       # Always set ignore_expiration to true when calling the decode_jwt method.
       CanvasSecurity.class_eval do
-        @old_decode_jwt = self.method(:decode_jwt)
+        @old_decode_jwt = method(:decode_jwt)
 
         def self.decode_jwt(body, keys = [])
           @old_decode_jwt.call(body, keys, ignore_expiration: true)
diff --git a/spec/controllers/lti/ims/names_and_roles_controller_spec.rb b/spec/controllers/lti/ims/names_and_roles_controller_spec.rb
index 6fce34912e7f2..62c1abb05fcaa 100644
--- a/spec/controllers/lti/ims/names_and_roles_controller_spec.rb
+++ b/spec/controllers/lti/ims/names_and_roles_controller_spec.rb
@@ -1268,7 +1268,7 @@ def custom_enrollment_in_course(base_type_name, opts = {})
   end
 
   def match_enrollment(*enrollment)
-    if self.respond_to?(:rlid_param) && rlid_param.present?
+    if respond_to?(:rlid_param) && rlid_param.present?
       match_enrollment_for_rlid({}, *enrollment)
     elsif enrollment.first.is_a?(Enrollment)
       be_lti_course_membership({ expected: enrollment })
diff --git a/spec/lib/canvas/apm_common.rb b/spec/lib/canvas/apm_common.rb
index 143d0cde6fa1d..93e170e113c6f 100644
--- a/spec/lib/canvas/apm_common.rb
+++ b/spec/lib/canvas/apm_common.rb
@@ -28,7 +28,7 @@ def initialize
           attr_accessor :resource, :span_type
 
           def initialize
-            self.reset!
+            reset!
           end
 
           def reset!
diff --git a/spec/messages/messages_helper.rb b/spec/messages/messages_helper.rb
index 6107e7d446315..cf7de9a9cc4ab 100644
--- a/spec/messages/messages_helper.rb
+++ b/spec/messages/messages_helper.rb
@@ -37,7 +37,7 @@ def generate_message(notification_name, path_type, *)
   include MessagesCommon
 
   def message_data_with_default
-    if self.respond_to?(:message_data)
+    if respond_to?(:message_data)
       message_data
     else
       {}
diff --git a/spec/models/assignment_spec.rb b/spec/models/assignment_spec.rb
index 25d0983a86d7c..15176644e495c 100644
--- a/spec/models/assignment_spec.rb
+++ b/spec/models/assignment_spec.rb
@@ -8122,7 +8122,7 @@ def assignment(group_category = nil)
         @called = false
         allow_any_instance_of(Submission).to receive(:assignment_muted_changed) do
           @called = true
-          expect(self.submission_model).to eq @submission
+          expect(submission_model).to eq @submission
         end
 
         @assignment.unmute!
diff --git a/spec/selenium/helpers/differentiated_assignments/da_assignment.rb b/spec/selenium/helpers/differentiated_assignments/da_assignment.rb
index 1e342b06287a4..4b17ebf9ec8ed 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_assignment.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_assignment.rb
@@ -26,7 +26,7 @@ class Assignment < SpecComponents::Assignment
 
     def initialize(assignees)
       initialize_assignees(assignees)
-      super(course: DifferentiatedAssignments.the_course, title: "Assignment for #{self.assignees_list}")
+      super(course: DifferentiatedAssignments.the_course, title: "Assignment for #{assignees_list}")
     end
   end
 end
diff --git a/spec/selenium/helpers/differentiated_assignments/da_course_modules_module.rb b/spec/selenium/helpers/differentiated_assignments/da_course_modules_module.rb
index ba9139876bd9c..56ee98f469065 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_course_modules_module.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_course_modules_module.rb
@@ -40,21 +40,21 @@ def create_course_module(module_name)
 
       def add_assignments_to_modules
         assignments = DifferentiatedAssignments::Homework::Assignments
-        self.first_module.add_assignment(assignments.assignment_for_section_a)
-        self.first_module.add_assignment(assignments.assignment_for_section_b)
-        self.first_module.add_assignment(assignments.assignment_for_first_student)
+        first_module.add_assignment(assignments.assignment_for_section_a)
+        first_module.add_assignment(assignments.assignment_for_section_b)
+        first_module.add_assignment(assignments.assignment_for_first_student)
 
         quizzes = DifferentiatedAssignments::Homework::Quizzes
-        self.second_module.add_quiz(quizzes.quiz_for_section_a)
-        self.second_module.add_quiz(quizzes.quiz_for_section_b)
-        self.second_module.add_quiz(quizzes.quiz_for_second_and_third_students)
+        second_module.add_quiz(quizzes.quiz_for_section_a)
+        second_module.add_quiz(quizzes.quiz_for_section_b)
+        second_module.add_quiz(quizzes.quiz_for_second_and_third_students)
 
         discussions = DifferentiatedAssignments::Homework::Discussions
-        self.third_module.add_discussion(discussions.discussion_for_section_a)
-        self.third_module.add_discussion(discussions.discussion_for_section_b)
-        self.third_module.add_discussion(discussions.discussion_for_first_student)
+        third_module.add_discussion(discussions.discussion_for_section_a)
+        third_module.add_discussion(discussions.discussion_for_section_b)
+        third_module.add_discussion(discussions.discussion_for_first_student)
 
-        self.fourth_module.add_assignment(assignments.assignment_for_section_c)
+        fourth_module.add_assignment(assignments.assignment_for_section_c)
       end
     end
   end
diff --git a/spec/selenium/helpers/differentiated_assignments/da_discussion.rb b/spec/selenium/helpers/differentiated_assignments/da_discussion.rb
index 113b10569665c..3e7ce1773ec96 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_discussion.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_discussion.rb
@@ -26,7 +26,7 @@ class Discussion < SpecComponents::Discussion
 
     def initialize(assignees)
       initialize_assignees(assignees)
-      super(course: DifferentiatedAssignments.the_course, title: "Discussion for #{self.assignees_list}")
+      super(course: DifferentiatedAssignments.the_course, title: "Discussion for #{assignees_list}")
     end
   end
 end
diff --git a/spec/selenium/helpers/differentiated_assignments/da_homework_assignments_module.rb b/spec/selenium/helpers/differentiated_assignments/da_homework_assignments_module.rb
index ca85b789bb2ee..88612879f901d 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_homework_assignments_module.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_homework_assignments_module.rb
@@ -52,20 +52,20 @@ def short_list_initialize
 
         def all
           [
-            self.assignment_for_everyone,
-            self.assignment_for_section_a,
-            self.assignment_for_section_b,
-            self.assignment_for_sections_a_and_b,
-            self.assignment_for_section_c,
-            self.assignment_for_first_student,
-            self.assignment_for_second_and_third_students
+            assignment_for_everyone,
+            assignment_for_section_a,
+            assignment_for_section_b,
+            assignment_for_sections_a_and_b,
+            assignment_for_section_c,
+            assignment_for_first_student,
+            assignment_for_second_and_third_students
           ]
         end
 
         def short_list
           [
-            self.assignment_for_sections_a_and_b,
-            self.assignment_for_second_and_third_students
+            assignment_for_sections_a_and_b,
+            assignment_for_second_and_third_students
           ]
         end
 
@@ -77,22 +77,22 @@ def create_assignment_for(assignee)
 
         def assign_assignment_overrides(short = false)
           if short
-            self.short_list.each(&:assign_overrides)
+            short_list.each(&:assign_overrides)
           else
-            self.all.each(&:assign_overrides)
+            all.each(&:assign_overrides)
           end
         end
 
         def submit_assignments
           users = DifferentiatedAssignments::Users
-          self.assignment_for_everyone.submit_as(users.first_student)
-          self.assignment_for_section_a.submit_as(users.first_student)
-          self.assignment_for_section_b.submit_as(users.second_student)
-          self.assignment_for_sections_a_and_b.submit_as(users.third_student)
-          self.assignment_for_section_c.submit_as(users.fourth_student)
-          self.assignment_for_first_student.submit_as(users.first_student)
-          self.assignment_for_second_and_third_students.submit_as(users.second_student)
-          self.assignment_for_second_and_third_students.submit_as(users.third_student)
+          assignment_for_everyone.submit_as(users.first_student)
+          assignment_for_section_a.submit_as(users.first_student)
+          assignment_for_section_b.submit_as(users.second_student)
+          assignment_for_sections_a_and_b.submit_as(users.third_student)
+          assignment_for_section_c.submit_as(users.fourth_student)
+          assignment_for_first_student.submit_as(users.first_student)
+          assignment_for_second_and_third_students.submit_as(users.second_student)
+          assignment_for_second_and_third_students.submit_as(users.third_student)
         end
       end
     end
diff --git a/spec/selenium/helpers/differentiated_assignments/da_homework_discussions_module.rb b/spec/selenium/helpers/differentiated_assignments/da_homework_discussions_module.rb
index 3a7c0e166e98d..c582c49d9d2ff 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_homework_discussions_module.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_homework_discussions_module.rb
@@ -51,20 +51,20 @@ def short_list_initialize
 
         def all
           [
-            self.discussion_for_everyone,
-            self.discussion_for_section_a,
-            self.discussion_for_section_b,
-            self.discussion_for_sections_a_and_b,
-            self.discussion_for_section_c,
-            self.discussion_for_first_student,
-            self.discussion_for_second_and_third_students
+            discussion_for_everyone,
+            discussion_for_section_a,
+            discussion_for_section_b,
+            discussion_for_sections_a_and_b,
+            discussion_for_section_c,
+            discussion_for_first_student,
+            discussion_for_second_and_third_students
           ]
         end
 
         def short_list
           [
-            self.discussion_for_sections_a_and_b,
-            self.discussion_for_second_and_third_students
+            discussion_for_sections_a_and_b,
+            discussion_for_second_and_third_students
           ]
         end
 
@@ -76,22 +76,22 @@ def create_discussion_for(assignee)
 
         def assign_discussion_overrides(short = false)
           if short
-            self.short_list.each(&:assign_overrides)
+            short_list.each(&:assign_overrides)
           else
-            self.all.each(&:assign_overrides)
+            all.each(&:assign_overrides)
           end
         end
 
         def submit_discussions
           users = DifferentiatedAssignments::Users
-          self.discussion_for_everyone.submit_as(users.first_student)
-          self.discussion_for_section_a.submit_as(users.first_student)
-          self.discussion_for_section_b.submit_as(users.second_student)
-          self.discussion_for_sections_a_and_b.submit_as(users.third_student)
-          self.discussion_for_section_c.submit_as(users.fourth_student)
-          self.discussion_for_first_student.submit_as(users.first_student)
-          self.discussion_for_second_and_third_students.submit_as(users.second_student)
-          self.discussion_for_second_and_third_students.submit_as(users.third_student)
+          discussion_for_everyone.submit_as(users.first_student)
+          discussion_for_section_a.submit_as(users.first_student)
+          discussion_for_section_b.submit_as(users.second_student)
+          discussion_for_sections_a_and_b.submit_as(users.third_student)
+          discussion_for_section_c.submit_as(users.fourth_student)
+          discussion_for_first_student.submit_as(users.first_student)
+          discussion_for_second_and_third_students.submit_as(users.second_student)
+          discussion_for_second_and_third_students.submit_as(users.third_student)
         end
       end
     end
diff --git a/spec/selenium/helpers/differentiated_assignments/da_homework_quizzes_module.rb b/spec/selenium/helpers/differentiated_assignments/da_homework_quizzes_module.rb
index 1041ca519ecff..3f9e62b8ed906 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_homework_quizzes_module.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_homework_quizzes_module.rb
@@ -50,20 +50,20 @@ def short_list_initialize
 
         def all
           [
-            self.quiz_for_everyone,
-            self.quiz_for_section_a,
-            self.quiz_for_section_b,
-            self.quiz_for_section_c,
-            self.quiz_for_sections_a_and_b,
-            self.quiz_for_first_student,
-            self.quiz_for_second_and_third_students
+            quiz_for_everyone,
+            quiz_for_section_a,
+            quiz_for_section_b,
+            quiz_for_section_c,
+            quiz_for_sections_a_and_b,
+            quiz_for_first_student,
+            quiz_for_second_and_third_students
           ]
         end
 
         def short_list
           [
-            self.quiz_for_sections_a_and_b,
-            self.quiz_for_second_and_third_students
+            quiz_for_sections_a_and_b,
+            quiz_for_second_and_third_students
           ]
         end
 
@@ -75,22 +75,22 @@ def create_quiz_for(assignee)
 
         def assign_quiz_overrides(short = flase)
           if short
-            self.short_list.each(&:assign_overrides)
+            short_list.each(&:assign_overrides)
           else
-            self.all.each(&:assign_overrides)
+            all.each(&:assign_overrides)
           end
         end
 
         def submit_quizzes
           users = DifferentiatedAssignments::Users
-          self.quiz_for_everyone.submit_as(users.first_student)
-          self.quiz_for_section_a.submit_as(users.first_student)
-          self.quiz_for_section_b.submit_as(users.second_student)
-          self.quiz_for_section_c.submit_as(users.fourth_student)
-          self.quiz_for_sections_a_and_b.submit_as(users.third_student)
-          self.quiz_for_first_student.submit_as(users.first_student)
-          self.quiz_for_second_and_third_students.submit_as(users.second_student)
-          self.quiz_for_second_and_third_students.submit_as(users.third_student)
+          quiz_for_everyone.submit_as(users.first_student)
+          quiz_for_section_a.submit_as(users.first_student)
+          quiz_for_section_b.submit_as(users.second_student)
+          quiz_for_section_c.submit_as(users.fourth_student)
+          quiz_for_sections_a_and_b.submit_as(users.third_student)
+          quiz_for_first_student.submit_as(users.first_student)
+          quiz_for_second_and_third_students.submit_as(users.second_student)
+          quiz_for_second_and_third_students.submit_as(users.third_student)
         end
       end
     end
diff --git a/spec/selenium/helpers/differentiated_assignments/da_quiz.rb b/spec/selenium/helpers/differentiated_assignments/da_quiz.rb
index 66e6b4b7fdc49..75bedfa1b9bf7 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_quiz.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_quiz.rb
@@ -26,7 +26,7 @@ class Quiz < SpecComponents::Quiz
 
     def initialize(assignees)
       initialize_assignees(assignees)
-      super(course: DifferentiatedAssignments.the_course, title: "Quiz for #{self.assignees_list}")
+      super(course: DifferentiatedAssignments.the_course, title: "Quiz for #{assignees_list}")
     end
   end
 end
diff --git a/spec/selenium/helpers/differentiated_assignments/da_users_module.rb b/spec/selenium/helpers/differentiated_assignments/da_users_module.rb
index f988ee575f468..f91b327449668 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_users_module.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_users_module.rb
@@ -110,28 +110,28 @@ def enroll_students
       end
 
       def enroll_first_student
-        student = self.first_student
+        student = first_student
         enroll_student_in_section_a(student)
-        add_user_to_group(group: self.student_group_x, user: student, is_leader: true)
+        add_user_to_group(group: student_group_x, user: student, is_leader: true)
       end
 
       def enroll_second_student
-        student = self.second_student
+        student = second_student
         enroll_student_in_section_b(student)
-        add_user_to_group(group: self.student_group_x, user: student)
+        add_user_to_group(group: student_group_x, user: student)
       end
 
       def enroll_third_student
-        student = self.third_student
+        student = third_student
         enroll_student_in_section_a(student)
         enroll_student_in_section_b(student)
-        add_user_to_group(group: self.student_group_y, user: student, is_leader: true)
+        add_user_to_group(group: student_group_y, user: student, is_leader: true)
       end
 
       def enroll_fourth_student
-        student = self.fourth_student
+        student = fourth_student
         enroll_student_in_section_c(student)
-        add_user_to_group(group: self.student_group_y, user: student)
+        add_user_to_group(group: student_group_y, user: student)
       end
 
       def enroll_student_in_section_a(student)
@@ -168,11 +168,11 @@ def enroll_observers
       end
 
       def enroll_first_observer
-        enroll_observer(self.first_observer, self.first_student)
+        enroll_observer(first_observer, first_student)
       end
 
       def enroll_third_observer
-        enroll_observer(self.third_observer, self.third_student)
+        enroll_observer(third_observer, third_student)
       end
 
       def enroll_observer(an_observer, student_to_observe)
diff --git a/spec/selenium/helpers/differentiated_assignments/da_wrappable.rb b/spec/selenium/helpers/differentiated_assignments/da_wrappable.rb
index a7bc415a847df..0a41da61d1ba2 100644
--- a/spec/selenium/helpers/differentiated_assignments/da_wrappable.rb
+++ b/spec/selenium/helpers/differentiated_assignments/da_wrappable.rb
@@ -46,7 +46,7 @@ def assignees_list
     end
 
     def assign_overrides
-      self.assignees.each { |assignee| assign_to(assignee) }
+      assignees.each { |assignee| assign_to(assignee) }
     end
 
     private
@@ -61,7 +61,7 @@ def validate_self
     end
 
     def validate_assignees
-      (DifferentiatedAssignments::HomeworkAssignee::ASSIGNEES & self.assignees).empty?
+      (DifferentiatedAssignments::HomeworkAssignee::ASSIGNEES & assignees).empty?
     end
 
     def assign_to(assignee)
@@ -90,8 +90,8 @@ def remove_word_from_array_items(an_array, word)
     end
 
     def assignees_by_type(type)
-      self.assignees.select { |a| a.include? type }
-          .sort
+      assignees.select { |a| a.include? type }
+               .sort
     end
   end
 end
diff --git a/spec/selenium/test_setup/selenium_extensions.rb b/spec/selenium/test_setup/selenium_extensions.rb
index 7c9fd0d437b8a..7ea36f3ff8b45 100644
--- a/spec/selenium/test_setup/selenium_extensions.rb
+++ b/spec/selenium/test_setup/selenium_extensions.rb
@@ -203,7 +203,7 @@ def wait_for(method:, timeout: self.timeout, ignore: nil, &block)
       end
 
       def disable
-        original_wait = self.timeout
+        original_wait = timeout
         self.timeout = 0
         yield
       ensure
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index b7b8e8bceaf99..c02457ebc9148 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -118,7 +118,7 @@ def run(example)
 Time.class_eval do
   def compare_with_round(other)
     other = Time.at(other.to_i, other.usec) if other.respond_to?(:usec)
-    Time.at(self.to_i, self.usec).compare_without_round(other)
+    Time.at(to_i, usec).compare_without_round(other)
   end
   alias_method :compare_without_round, :<=>
   alias_method :<=>, :compare_with_round
@@ -131,7 +131,7 @@ def compare_with_round(other)
 # has already been built, and I can't put myself between the two
 module ActionView::TestCase::Behavior
   def view_assigns
-    if self.is_a?(RSpec::Rails::HelperExampleGroup)
+    if is_a?(RSpec::Rails::HelperExampleGroup)
       # the original implementation. we can't call super because
       # we replaced the whole original method
       return _user_defined_ivars.map do |ivar|