From ff99d1813848f2b926ddb4d62e9cef1b8d0fb2dd Mon Sep 17 00:00:00 2001
From: Cody Cutrer
#{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}")
+ :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 = ""
- 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 += "
"
@@ -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", before_date).delete_all
+ where("created_at", before_date).delete_all
end
def self.categories
diff --git a/app/models/etherpad_collaboration.rb b/app/models/etherpad_collaboration.rb
index 11507cb216ceb..839910ff61b6e 100644
--- a/app/models/etherpad_collaboration.rb
+++ b/app/models/etherpad_collaboration.rb
@@ -36,7 +36,7 @@ def style_class
# /ep/pad/view/PAD_ID/latest read-only view (still reveals pad id)
def initialize_document
- self.url ||= "http://#{EtherpadCollaboration.config[:domain]}/i-#{self.uuid}"
+ self.url ||= "http://#{EtherpadCollaboration.config[:domain]}/i-#{uuid}"
end
def self.config
diff --git a/app/models/external_feed.rb b/app/models/external_feed.rb
index 41ba87f6bc00d..95e6eb42b5150 100644
--- a/app/models/external_feed.rb
+++ b/app/models/external_feed.rb
@@ -41,7 +41,7 @@ class ExternalFeed < ActiveRecord::Base
def infer_defaults
self.consecutive_failures ||= 0
self.refresh_at ||= Time.now.utc
- unless VERBOSITIES.include?(self.verbosity)
+ unless VERBOSITIES.include?(verbosity)
self.verbosity = "full"
end
true
@@ -49,8 +49,8 @@ def infer_defaults
protected :infer_defaults
def display_name(short = true)
- short_url = (self.url || "").split("/")[0, 3].join("/")
- self.title || (short ? t(:short_feed_title, "%{short_url} feed", :short_url => 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{
') + 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', cutoff).where.not(feature: valid_features) delete_scope.in_batches.delete_all diff --git a/lib/feature_flags.rb b/lib/feature_flags.rb index 74a62ffdf4879..32b9494b8928e 100644 --- a/lib/feature_flags.rb +++ b/lib/feature_flags.rb @@ -66,11 +66,11 @@ def disable_feature!(feature) end def reset_feature!(feature) - self.feature_flags.where(feature: feature.to_s).destroy_all + feature_flags.where(feature: feature.to_s).destroy_all end def feature_flag_cache_key(feature) - ['feature_flag3', self.class.name, self.global_id, feature.to_s].cache_key + ['feature_flag3', self.class.name, global_id, feature.to_s].cache_key end def feature_flag_cache @@ -80,13 +80,13 @@ def feature_flag_cache # return the feature flag for the given feature that is defined on this object, if any. # (helper method. use lookup_feature_flag to test policy.) def feature_flag(feature, skip_cache: false) - return nil unless self.id + return nil unless id - self.shard.activate do - if self.feature_flags.loaded? - self.feature_flags.detect { |ff| ff.feature == feature.to_s } + shard.activate do + if feature_flags.loaded? + feature_flags.detect { |ff| ff.feature == feature.to_s } elsif skip_cache - self.feature_flags.where(feature: feature.to_s).first + feature_flags.where(feature: feature.to_s).first else result = RequestCache.cache("feature_flag", self, feature) do feature_flag_cache.fetch(feature_flag_cache_key(feature)) do @@ -136,8 +136,8 @@ def lookup_feature_flag(feature, override_hidden: false, skip_cache: false, hide return nil if feature_def.visible_on.is_a?(Proc) && !feature_def.visible_on.call(self) return return_flag(feature_def, hide_inherited_enabled) unless feature_def.can_override? || feature_def.hidden? - is_root_account = self.is_a?(Account) && self.root_account? - is_site_admin = self.is_a?(Account) && self.site_admin? + is_root_account = is_a?(Account) && root_account? + is_site_admin = is_a?(Account) && site_admin? # inherit the feature definition as a default unless it's a hidden feature retval = feature_def.clone_for_cache unless feature_def.hidden? && !is_site_admin && !override_hidden @@ -154,7 +154,7 @@ def lookup_feature_flag(feature, override_hidden: false, skip_cache: false, hide account = Account.new account.id = id - account.shard = Shard.shard_for(id, self.shard) + account.shard = Shard.shard_for(id, shard) account.readonly! account end @@ -175,7 +175,7 @@ def lookup_feature_flag(feature, override_hidden: false, skip_cache: false, hide (retval.default? || (retval.context_type == 'Account' && retval.context_id == Account.site_admin.id)) if is_root_account # create a virtual feature flag in corresponding default state state - retval = self.feature_flags.temp_record feature: feature, state: 'off' unless retval.hidden? + retval = feature_flags.temp_record feature: feature, state: 'off' unless retval.hidden? else # the feature doesn't exist beneath the root account until the root account opts in if inherited_only @@ -195,7 +195,7 @@ def return_flag(retval, hide_inherited_enabled) unless hide_inherited_enabled && retval.enabled? && !retval.can_override? && ( # Hide feature flag configs if they belong to a different context - (!retval.default? && (retval.context_type != self.class.name || retval.context_id != self.id)) || + (!retval.default? && (retval.context_type != self.class.name || retval.context_id != id)) || # Hide flags that are forced on in config as well retval.default? ) diff --git a/lib/feature_flags/loader.rb b/lib/feature_flags/loader.rb index 60c6eb7b1e070..b3dd2c2006243 100644 --- a/lib/feature_flags/loader.rb +++ b/lib/feature_flags/loader.rb @@ -77,9 +77,9 @@ def self.load_yaml_files end def self.load_feature_flags - definitions = self.load_yaml_files + definitions = load_yaml_files definitions.each do |name, definition| - self.load_definition(name, definition) + load_definition(name, definition) end end diff --git a/lib/file_splitter.rb b/lib/file_splitter.rb index 4991a0f280969..887fc0a6b9edc 100644 --- a/lib/file_splitter.rb +++ b/lib/file_splitter.rb @@ -27,7 +27,7 @@ def format # Send it a block, expects @txt to be set in the parser. def each_entry(&block) - self.send format, &block + send format, &block end def each_line(&block) diff --git a/lib/gradebook_importer.rb b/lib/gradebook_importer.rb index 1d5a6c993596c..ebefb5c926414 100644 --- a/lib/gradebook_importer.rb +++ b/lib/gradebook_importer.rb @@ -55,7 +55,7 @@ def course_score? :submissions, :missing_assignments, :missing_students, :upload def self.create_from(progress, gradebook_upload, user, attachment) - self.new(gradebook_upload, attachment, user, progress).parse! + new(gradebook_upload, attachment, user, progress).parse! rescue CSV::MalformedCSVError => 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|