RuboCop: Style/CaseLikeIf

[skip-stages=Flakey]

auto-corrected

Change-Id: I1f6b8a5f58a97a3ef17004ba9bf7a0940632dd55
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/278161
Tested-by: Service Cloud Jenkins <svc.cloudjenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
QA-Review: Cody Cutrer <cody@instructure.com>
Product-Review: Cody Cutrer <cody@instructure.com>
This commit is contained in:
Cody Cutrer 2021-11-12 09:43:00 -07:00
parent 2b3a208f9a
commit fd6b50710c
106 changed files with 523 additions and 367 deletions

View File

@ -132,6 +132,8 @@ Specs/EnsureSpecExtension:
Style/Alias:
EnforcedStyle: prefer_alias_method # https://github.com/rubocop/ruby-style-guide/issues/821
Severity: error
Style/CaseLikeIf:
Severity: error
Style/ColonMethodCall:
Severity: error
Style/ConditionalAssignment:

View File

@ -624,11 +624,12 @@ class AccountsController < ApplicationController
sortable_name_col = User.sortable_name_order_by_clause('users')
order = if params[:sort] == 'course_name'
order = case params[:sort]
when 'course_name'
Course.best_unicode_collation_key('courses.name').to_s
elsif params[:sort] == 'sis_course_id'
when 'sis_course_id'
"courses.sis_source_id"
elsif params[:sort] == 'teacher'
when 'teacher'
"(SELECT #{sortable_name_col} FROM #{User.quoted_table_name}
JOIN #{Enrollment.quoted_table_name} on users.id = enrollments.user_id
WHERE enrollments.workflow_state <> 'deleted'
@ -636,10 +637,10 @@ class AccountsController < ApplicationController
AND enrollments.course_id = courses.id
ORDER BY #{sortable_name_col} LIMIT 1)"
# leaving subaccount as an option for backwards compatibility
elsif params[:sort] == 'subaccount' || params[:sort] == 'account_name'
when 'subaccount', 'account_name'
"(SELECT #{Account.best_unicode_collation_key('accounts.name')} FROM #{Account.quoted_table_name}
WHERE accounts.id = courses.account_id)"
elsif params[:sort] == 'term'
when 'term'
"(SELECT #{EnrollmentTerm.best_unicode_collation_key('enrollment_terms.name')}
FROM #{EnrollmentTerm.quoted_table_name}
WHERE enrollment_terms.id = courses.enrollment_term_id)"

View File

@ -77,10 +77,11 @@ class AnnouncementsController < ApplicationController
feed_key = @context.asset_string
end
if feed_key
if @context.is_a?(Course)
case @context
when Course
content_for_head helpers.auto_discovery_link_tag(:atom, feeds_announcements_format_path(feed_key, :atom), { :title => t(:feed_title_course, "Course Announcements Atom Feed") })
content_for_head helpers.auto_discovery_link_tag(:rss, feeds_announcements_format_path(feed_key, :rss), { :title => t(:podcast_title_course, "Course Announcements Podcast Feed") })
elsif @context.is_a?(Group)
when Group
content_for_head helpers.auto_discovery_link_tag(:atom, feeds_announcements_format_path(feed_key, :atom), { :title => t(:feed_title_group, "Group Announcements Atom Feed") })
content_for_head helpers.auto_discovery_link_tag(:rss, feeds_announcements_format_path(feed_key, :rss), { :title => t(:podcast_title_group, "Group Announcements Podcast Feed") })
end
@ -119,9 +120,10 @@ class AnnouncementsController < ApplicationController
rss = RSS::Rss.new("2.0")
channel = RSS::Rss::Channel.new
channel.title = t(:podcast_feed_name, "%{course} Announcements Podcast Feed", :course => @context.name)
if @context.is_a?(Course)
case @context
when Course
channel.description = t(:podcast_feed_description_course, "Any media files linked from or embedded within announcements in the course \"%{course}\" will appear in this feed.", :course => @context.name)
elsif @context.is_a?(Group)
when Group
channel.description = t(:podcast_feed_description_group, "Any media files linked from or embedded within announcements in the group \"%{group}\" will appear in this feed.", :group => @context.name)
end
channel.link = polymorphic_url([@context, :announcements])

View File

@ -780,11 +780,12 @@ class ApplicationController < ActionController::Base
end
def tab_disabled_message(context)
if context.is_a?(Account)
case context
when Account
t "#application.notices.page_disabled_for_account", "That page has been disabled for this account"
elsif context.is_a?(Course)
when Course
t "#application.notices.page_disabled_for_course", "That page has been disabled for this course"
elsif context.is_a?(Group)
when Group
t "#application.notices.page_disabled_for_group", "That page has been disabled for this group"
else
t "#application.notices.page_disabled", "That page has been disabled"
@ -1215,13 +1216,14 @@ class ApplicationController < ActionController::Base
redirect ||= root_url
get_quota(context)
if response.body.size + @quota_used > @quota
error = if context.is_a?(Account)
error = case context
when Account
t "#application.errors.quota_exceeded_account", "Account storage quota exceeded"
elsif context.is_a?(Course)
when Course
t "#application.errors.quota_exceeded_course", "Course storage quota exceeded"
elsif context.is_a?(Group)
when Group
t "#application.errors.quota_exceeded_group", "Group storage quota exceeded"
elsif context.is_a?(User)
when User
t "#application.errors.quota_exceeded_user", "User storage quota exceeded"
else
t "#application.errors.quota_exceeded", "Storage quota exceeded"
@ -1248,7 +1250,8 @@ class ApplicationController < ActionController::Base
end
@context = nil
@problem = nil
if pieces[0] == "enrollment"
case pieces[0]
when "enrollment"
@enrollment = Enrollment.where(uuid: pieces[1]).first if pieces[1]
@context_type = "Course"
if !@enrollment
@ -1258,7 +1261,7 @@ class ApplicationController < ActionController::Base
end
@context = @enrollment.course unless @problem
@current_user = @enrollment.user unless @problem
elsif pieces[0] == 'group_membership'
when 'group_membership'
@membership = GroupMembership.active.where(uuid: pieces[1]).first if pieces[1]
@context_type = "Group"
if !@membership
@ -1268,7 +1271,7 @@ class ApplicationController < ActionController::Base
end
@context = @membership.group unless @problem
@current_user = @membership.user unless @problem
elsif pieces[0] == 'user'
when 'user'
find_user_from_uuid(pieces[1])
@problem = t "#application.errors.invalid_verification_code", "The verification code is invalid." unless @current_user
@context = @current_user
@ -1281,9 +1284,10 @@ class ApplicationController < ActionController::Base
if !@context
@problem = t "#application.errors.invalid_verification_code", "The verification code is invalid."
elsif (!@context.is_public rescue false) && (!@context.respond_to?(:uuid) || pieces[1] != @context.uuid)
@problem = if @context_type == 'course'
@problem = case @context_type
when 'course'
t "#application.errors.feed_private_course", "The matching course has gone private, so public feeds like this one will no longer be visible."
elsif @context_type == 'group'
when 'group'
t "#application.errors.feed_private_group", "The matching group has gone private, so public feeds like this one will no longer be visible."
else
t "#application.errors.feed_private", "The matching context has gone private, so public feeds like this one will no longer be visible."

View File

@ -761,9 +761,10 @@ class CalendarEventsApiController < ApplicationController
# find the context associated with the appointment..
event_context = @contexts.find do |context|
effective_context_code =
if context.is_a?(Course)
case context
when Course
"course_" + context.id.to_s
elsif context.is_a?(Group)
when Group
"group_" + context.id.to_s
end
!effective_context_code.nil? && appointment.effective_context_code.eql?(effective_context_code)
@ -1379,9 +1380,10 @@ class CalendarEventsApiController < ApplicationController
def set_duplicate_params(event_attributes, options = {})
options[:iterator] ||= 0
offset_interval = options[:interval] * options[:iterator]
offset = if options[:frequency] == "monthly"
offset = case options[:frequency]
when "monthly"
offset_interval.months
elsif options[:frequency] == "daily"
when "daily"
offset_interval.days
else
offset_interval.weeks

View File

@ -125,9 +125,10 @@ class CalendarEventsController < ApplicationController
protected
def feature_context
if @context.is_a?(User)
case @context
when User
@domain_root_account
elsif @context.is_a?(Group)
when Group
@context.context
else
@context

View File

@ -51,7 +51,8 @@ class ContentExportsController < ApplicationController
export.user = @current_user
export.workflow_state = 'created'
if @context.is_a?(Course)
case @context
when Course
if params[:export_type] == 'qti'
export.export_type = ContentExport::QTI
export.selected_content = params[:copy].to_unsafe_h
@ -59,7 +60,7 @@ class ContentExportsController < ApplicationController
export.export_type = ContentExport::COMMON_CARTRIDGE
export.selected_content = { :everything => true }
end
elsif @context.is_a?(User)
when User
export.export_type = ContentExport::USER_DATA
end

View File

@ -65,7 +65,8 @@ class ContextController < ApplicationController
log_asset_access(["roster", @context], 'roster', 'other')
if @context.is_a?(Course)
case @context
when Course
return unless tab_enabled?(Course::TAB_PEOPLE)
if @context.concluded?
@ -128,7 +129,7 @@ class ContextController < ApplicationController
if @context.grants_right?(@current_user, session, :read_as_admin)
set_student_context_cards_js_env
end
elsif @context.is_a?(Group)
when Group
@users = if @context.grants_right?(@current_user, :read_as_admin)
@context.participating_users.distinct.order_by_sortable_name
else
@ -213,7 +214,8 @@ class ContextController < ApplicationController
raise ActiveRecord::RecordNotFound unless Api::ID_REGEX.match?(params[:id])
user_id = Shard.relative_id_for(params[:id], Shard.current, @context.shard)
if @context.is_a?(Course)
case @context
when Course
is_admin = @context.grants_right?(@current_user, session, :read_as_admin)
scope = @context.enrollments_visible_to(@current_user, :include_concluded => is_admin).where(user_id: user_id)
scope = scope.active_or_pending unless is_admin
@ -230,16 +232,17 @@ class ContextController < ApplicationController
log_asset_access(@membership, "roster", "roster")
end
elsif @context.is_a?(Group)
when Group
@membership = @context.group_memberships.active.where(user_id: user_id).first
@enrollments = []
end
@user = @membership.user rescue nil
unless @user
if @context.is_a?(Course)
case @context
when Course
flash[:error] = t('no_user.course', "That user does not exist or is not currently a member of this course")
elsif @context.is_a?(Group)
when Group
flash[:error] = t('no_user.group', "That user does not exist or is not currently a member of this group")
end
redirect_to named_context_url(@context, :context_users_url)

View File

@ -1935,15 +1935,16 @@ class CoursesController < ApplicationController
locks_hash = Rails.cache.fetch(['locked_for_results', @current_user, Digest::MD5.hexdigest(params[:assets])].cache_key) do
locks = {}
types.each do |type, ids|
if type == 'assignment'
case type
when 'assignment'
@context.assignments.active.where(id: ids).each do |assignment|
locks[assignment.asset_string] = assignment.locked_for?(@current_user)
end
elsif type == 'quiz'
when 'quiz'
@context.quizzes.active.include_assignment.where(id: ids).each do |quiz|
locks[quiz.asset_string] = quiz.locked_for?(@current_user)
end
elsif type == 'discussion_topic'
when 'discussion_topic'
@context.discussion_topics.active.where(id: ids).each do |topic|
locks[topic.asset_string] = topic.locked_for?(@current_user)
end

View File

@ -553,9 +553,10 @@ class DiscussionTopicsController < ApplicationController
end
sections =
if section_visibilities == :none
case section_visibilities
when :none
[]
elsif section_visibilities == :all
when :all
@context.course_sections.active.to_a
else
@context.course_sections.select { |s| s.active? && section_visibilities.include?(s.id) }
@ -1171,9 +1172,10 @@ class DiscussionTopicsController < ApplicationController
visibilities = @context.course_section_visibility(@current_user)
invalid_sections =
if visibilities == :all
case visibilities
when :all
[]
elsif visibilities == :none
when :none
@topic.course_sections.map(&:id)
else
@topic.course_sections.map(&:id) - visibilities

View File

@ -244,9 +244,10 @@ class ExternalToolsController < ApplicationController
end
launch_type = params[:launch_type]
if launch_type == 'module_item'
case launch_type
when 'module_item'
generate_module_item_sessionless_launch
elsif launch_type == 'assessment'
when 'assessment'
generate_assignment_sessionless_launch
else
generate_common_sessionless_launch(options: { launch_url: params[:url] })

View File

@ -375,11 +375,12 @@ class FilesController < ApplicationController
@contexts = [@context]
get_all_pertinent_contexts(include_groups: true, cross_shard: true) if @context == @current_user
files_contexts = @contexts.map do |context|
tool_context = if context.is_a?(Course)
tool_context = case context
when Course
context
elsif context.is_a?(User)
when User
@domain_root_account
elsif context.is_a?(Group)
when Group
context.context
end
@ -1040,9 +1041,10 @@ class FilesController < ApplicationController
def api_file_status
@attachment = Attachment.where(id: params[:id], uuid: params[:uuid]).first!
if @attachment.file_state == 'available'
case @attachment.file_state
when 'available'
render :json => { :upload_status => 'ready', :attachment => attachment_json(@attachment, @current_user) }
elsif @attachment.file_state == 'deleted'
when 'deleted'
render :json => { :upload_status => 'pending' }
else
render :json => { :upload_status => 'errored', :message => @attachment.upload_error_message }

View File

@ -73,9 +73,10 @@ class GradebookSettingsController < ApplicationController
def nilify_strings(hash)
massaged_hash = {}
hash.each do |key, value|
massaged_hash[key] = if value == 'null'
massaged_hash[key] = case value
when 'null'
nil
elsif value.is_a? Hash
when Hash
nilify_strings(value)
else
value

View File

@ -128,11 +128,12 @@ class OAuth2ProviderController < ApplicationController
client_id = params[:client_id].presence || basic_user
secret = params[:client_secret].presence || basic_pass
granter = if grant_type == "authorization_code"
granter = case grant_type
when "authorization_code"
Canvas::OAuth::GrantTypes::AuthorizationCode.new(client_id, secret, params)
elsif grant_type == "refresh_token"
when "refresh_token"
Canvas::OAuth::GrantTypes::RefreshToken.new(client_id, secret, params)
elsif grant_type == 'client_credentials'
when 'client_credentials'
Canvas::OAuth::GrantTypes::ClientCredentials.new(params, request.host_with_port, request.protocol)
else
Canvas::OAuth::GrantTypes::BaseType.new(client_id, secret, params)

View File

@ -125,9 +125,10 @@ class OutcomesController < ApplicationController
def user_outcome_results
user_id = params[:user_id]
@user = if @context.is_a?(User)
@user = case @context
when User
@context
elsif @context.is_a?(Course)
when Course
@context.users.find(user_id)
else
@context.all_users.find_by!(id: user_id)

View File

@ -373,7 +373,8 @@ class SisApiController < ApplicationController
end
def published_course_ids
if context.is_a?(Account)
case context
when Account
course_scope = Course.published.where(account_id: [context.id] + Account.sub_account_ids_recursive(context.id))
if (starts_before = CanvasTime.try_parse(params[:starts_before]))
course_scope = course_scope.where("
@ -390,7 +391,7 @@ class SisApiController < ApplicationController
course_scope = course_scope.joins(:enrollment_term)
end
course_scope
elsif context.is_a?(Course)
when Course
[context.id]
end
end

View File

@ -259,12 +259,13 @@ class UsersController < ApplicationController
return redirect_to(user_profile_url(@current_user))
end
return_to_url = params[:return_to] || user_profile_url(@current_user)
if params[:service] == "google_drive"
case params[:service]
when "google_drive"
redirect_uri = oauth_success_url(:service => 'google_drive')
session[:oauth_gdrive_nonce] = SecureRandom.hex
state = Canvas::Security.create_jwt(redirect_uri: redirect_uri, return_to_url: return_to_url, nonce: session[:oauth_gdrive_nonce])
redirect_to GoogleDrive::Client.auth_uri(google_drive_client, state)
elsif params[:service] == "twitter"
when "twitter"
success_url = oauth_success_url(:service => 'twitter')
request_token = Twitter::Connection.request_token(success_url)
OAuthRequest.create(

View File

@ -58,17 +58,19 @@ class Loaders::DiscussionEntryCountsLoader < GraphQL::Batch::Loader
end
def object_specific_hash(objects)
if objects.first.is_a?(DiscussionTopic)
case objects.first
when DiscussionTopic
{ discussion_topic_id: objects }
elsif objects.first.is_a?(DiscussionEntry)
when DiscussionEntry
{ root_entry_id: objects }
end
end
def object_id_string(object)
if object.is_a?(DiscussionTopic)
case object
when DiscussionTopic
'discussion_topic_id'
elsif object.is_a?(DiscussionEntry)
when DiscussionEntry
'root_entry_id'
end
end

View File

@ -129,9 +129,10 @@ class Mutations::UpdateNotificationPreferences < Mutations::BaseMutation
end
def get_context(input)
if input[:context_type] == 'Course'
case input[:context_type]
when 'Course'
Course.find(input[:course_id]) if input[:course_id]
elsif input[:context_type] == 'Account'
when 'Account'
Account.find(input[:account_id]) if input[:account_id]
end
end

View File

@ -82,9 +82,10 @@ module Types
"This object specifies what students this override applies to",
null: true
def set
if override.set_type == "ADHOC"
case override.set_type
when "ADHOC"
override
elsif override.set_type == 'Noop'
when 'Noop'
Noop.new(override.set_id)
else
load_association(:set)

View File

@ -959,9 +959,10 @@ module ApplicationHelper
raise ArgumentError, "format must be one of #{ACCEPTABLE_FORMAT_TYPES.join(',')}"
end
if format == 'date'
case format
when 'date'
I18n.t('#helpers.accessible_date_only_format', 'YYYY-MM-DD')
elsif format == 'time'
when 'time'
I18n.t('#helpers.accessible_time_only_format', 'hh:mm')
else
I18n.t('#helpers.accessible_date_format', 'YYYY-MM-DD hh:mm')
@ -1061,7 +1062,8 @@ module ApplicationHelper
@csp_context_is_submission = false
attachment = @attachment || @context
if attachment.is_a?(Attachment)
if attachment.context_type == 'User'
case attachment.context_type
when 'User'
# search for an attachment association
aas =
attachment
@ -1078,10 +1080,10 @@ module ApplicationHelper
@csp_context_is_submission = true
courses.first
end
elsif attachment.context_type == 'Submission'
when 'Submission'
@csp_context_is_submission = true
attachment.submission.assignment.course
elsif attachment.context_type == 'Course'
when 'Course'
attachment.course
else
brand_config_account

View File

@ -77,9 +77,10 @@ module AvatarHelper
end
def avatar_url_for(conversation, participants = conversation.participants)
if participants.size == 1
case participants.size
when 1
avatar_url_for_user(participants.first)
elsif participants.size == 2
when 2
avatar_url_for_user(participants.find { |u| u.id != conversation.user_id })
else
avatar_url_for_group

View File

@ -20,9 +20,10 @@
module CyoeHelper
def cyoe_able?(item)
if item.content_type == 'Assignment'
case item.content_type
when 'Assignment'
item.graded? && item.content.graded?
elsif item.content_type == 'Quizzes::Quiz'
when 'Quizzes::Quiz'
item.graded? && item.content.assignment?
else
item.graded?

View File

@ -107,7 +107,8 @@ module SearchHelper
end
end
if context.is_a?(Course)
case context
when Course
add_courses.call [context], :current
visibility = context.enrollment_visibility_level_for(@current_user, context.section_visibilities_for(@current_user), require_message_permission: true)
sections = case visibility
@ -120,12 +121,12 @@ module SearchHelper
end
add_sections.call sections
add_groups.call context.groups.active, context
elsif context.is_a?(Group)
when Group
if context.grants_right?(@current_user, session, :read)
add_groups.call [context]
add_courses.call [context.context], :current if context.context.is_a?(Course)
end
elsif context.is_a?(CourseSection)
when CourseSection
visibility = context.course.enrollment_visibility_level_for(@current_user, context.course.section_visibilities_for(@current_user), require_message_permission: true)
sections = visibility == :restricted ? [] : [context]
add_courses.call [context.course], :current

View File

@ -52,7 +52,8 @@ module StreamItemsHelper
next unless supported_categories.include?(category)
if category == "Conversation"
case category
when "Conversation"
participant = user.conversation_participant(item.asset_id)
next if participant.nil? || participant.last_message.nil? || participant.last_author?
@ -63,7 +64,7 @@ module StreamItemsHelper
# the workflow_state on the stream_item_instance, that workflow_state
# may be out of sync with the underlying conversation.
item.unread = participant.unread?
elsif category == "AssessmentRequest"
when "AssessmentRequest"
next unless item.data.asset.grants_right?(user, :read)
end

View File

@ -71,9 +71,10 @@ class Alert < ActiveRecord::Base
def as_json(**)
converted_recipients = self.recipients.to_a.map do |recipient|
if recipient.is_a?(String)
case recipient
when String
find_role_by_name(recipient).id
elsif recipient.is_a?(Hash)
when Hash
recipient[:role_id]
else
":#{recipient}"

View File

@ -161,14 +161,15 @@ class AssessmentQuestion < ActiveRecord::Base
# or gets the relative path at the end of one like: /courses/15395/file_contents/course%20files/unfiled/test.jpg
deep_translate = lambda do |obj|
if obj.is_a?(Hash)
case obj
when Hash
obj.inject(HashWithIndifferentAccess.new) { |h, (k, v)|
h[k] = deep_translate.call(v)
h
}
elsif obj.is_a?(Array)
when Array
obj.map { |v| deep_translate.call(v) }
elsif obj.is_a?(String)
when String
obj.gsub(translate_link_regex) do |match|
translate_file_link(match, $~)
end

View File

@ -245,9 +245,10 @@ class AssignmentOverride < ActiveRecord::Base
end
def set
if self.set_type == 'ADHOC'
case self.set_type
when 'ADHOC'
assignment_override_students.preload(:user).map(&:user)
elsif self.set_type == SET_TYPE_NOOP
when SET_TYPE_NOOP
nil
else
super

View File

@ -172,9 +172,10 @@ class Attachment < ActiveRecord::Base
end
def find_with_possibly_replaced(a_or_as)
if a_or_as.is_a?(Attachment)
case a_or_as
when Attachment
find_attachment_possibly_replaced(a_or_as)
elsif a_or_as.is_a?(Array)
when Array
a_or_as.map { |a| find_attachment_possibly_replaced(a) }
end
end

View File

@ -31,9 +31,10 @@ class BookmarkService < UserService
description = opts[:comments] || ""
tags = opts[:tags] || ['instructure']
begin
if self.service == 'delicious'
case self.service
when 'delicious'
delicious_post_bookmark(self, url, title, description, tags)
elsif self.service == 'diigo'
when 'diigo'
Diigo::Connection.diigo_post_bookmark(self, url, title, description, tags)
end
rescue
@ -55,7 +56,8 @@ class BookmarkService < UserService
def bookmark_search(service, query)
bookmarks = []
if service.service == 'diigo'
case service.service
when 'diigo'
data = Diigo::Connection.diigo_get_bookmarks(service)
if data.class == Array and data.first.is_a?(Hash)
data.each do |bookmark|
@ -69,7 +71,7 @@ class BookmarkService < UserService
else
bookmarks
end
elsif service.service == 'delicious'
when 'delicious'
# This needs to be rewritten with new API and moved into a gem. (Currently not working and no way to test without updating the API.)
url = "https://api.del.icio.us/v1/posts/all?tag=#{query}"
http, request = delicious_generate_request(url, 'GET', service.service_user_name, service.decrypted_password)

View File

@ -289,11 +289,12 @@ class CommunicationChannel < ActiveRecord::Base
# 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
if self.path_type == TYPE_TWITTER
case self.path_type
when TYPE_TWITTER
res = self.user.user_services.for_service(TYPE_TWITTER).first.service_user_name rescue nil
res ||= t :default_twitter_handle, 'Twitter Handle'
res
elsif self.path_type == TYPE_PUSH
when TYPE_PUSH
t 'For All Devices'
else
self.path

View File

@ -220,7 +220,8 @@ class ContentTag < ActiveRecord::Base
end
def content_type_class(is_student = false)
if self.content_type == 'Assignment'
case self.content_type
when 'Assignment'
if self.content && self.content.submission_types == 'online_quiz'
is_student ? 'lti-quiz' : 'quiz'
elsif self.content && self.content.submission_types == 'discussion_topic'
@ -230,7 +231,7 @@ class ContentTag < ActiveRecord::Base
else
'assignment'
end
elsif self.content_type == 'Quizzes::Quiz'
when 'Quizzes::Quiz'
is_student ? 'lti-quiz' : 'quiz'
else
self.content_type.underscore

View File

@ -706,13 +706,14 @@ class ContextExternalTool < ActiveRecord::Base
settings.keys.each do |setting|
next if [:custom_fields, :environments].include? setting.to_sym
if settings[setting].is_a?(Hash)
case settings[setting]
when Hash
settings[setting].keys.each do |property|
if settings[setting][property].match?(URI::DEFAULT_PARSER.make_regexp)
settings[setting][property] = replace_host.call(settings[setting][property], new_domain)
end
end
elsif settings[setting].match?(URI::DEFAULT_PARSER.make_regexp)
when URI::DEFAULT_PARSER.make_regexp
settings[setting] = replace_host.call(settings[setting], new_domain)
end
end
@ -1210,9 +1211,10 @@ class ContextExternalTool < ActiveRecord::Base
scope = Assignment.active.joins(:external_tool_tag)
# limit to assignments in the tool's context
if context.is_a? Course
case context
when Course
scope = scope.where(context_id: context.id)
elsif context.is_a? Account
when Account
scope = scope.where(root_account_id: root_account_id, content_tags: { root_account_id: root_account_id })
end

View File

@ -453,12 +453,13 @@ class ContextModule < ActiveRecord::Base
def prerequisites=(prereqs)
Rails.cache.delete(['module_names', context].cache_key) # ensure the module list is up to date
if prereqs.is_a?(Array)
case prereqs
when Array
# validate format, skipping invalid ones
prereqs = prereqs.select do |pre|
pre.key?(:id) && pre.key?(:name) && pre[:type] == 'context_module'
end
elsif prereqs.is_a?(String)
when String
res = []
module_names = ContextModule.module_names(self.context)
pres = prereqs.split(",")
@ -635,21 +636,23 @@ class ContextModule < ActiveRecord::Base
params[:type] = params[:type].underscore if params[:type]
position = opts[:position] || ((self.content_tags.not_deleted.maximum(:position) || 0) + 1)
position = [position, params[:position].to_i].max if params[:position]
if params[:type] == "wiki_page" || params[:type] == "page"
case params[:type]
when "wiki_page", "page"
item = opts[:wiki_page] || self.context.wiki_pages.where(id: params[:id]).first
elsif params[:type] == "attachment" || params[:type] == "file"
when "attachment", "file"
item = opts[:attachment] || self.context.attachments.not_deleted.find_by_id(params[:id])
elsif params[:type] == "assignment"
when "assignment"
item = opts[:assignment] || self.context.assignments.active.where(id: params[:id]).first
item = item.submittable_object if item.respond_to?(:submittable_object) && item.submittable_object
elsif params[:type] == "discussion_topic" || params[:type] == "discussion"
when "discussion_topic", "discussion"
item = opts[:discussion_topic] || self.context.discussion_topics.active.where(id: params[:id]).first
elsif params[:type] == "quiz"
when "quiz"
item = opts[:quiz] || self.context.quizzes.active.where(id: params[:id]).first
end
workflow_state = ContentTag.asset_workflow_state(item) if item
workflow_state ||= 'active'
if params[:type] == 'external_url'
case params[:type]
when 'external_url'
title = params[:title]
added_item ||= self.content_tags.build(:context => self.context)
added_item.attributes = {
@ -667,7 +670,7 @@ class ContextModule < ActiveRecord::Base
added_item.workflow_state = 'unpublished' if added_item.new_record?
added_item.save
added_item
elsif params[:type] == 'context_external_tool' || params[:type] == 'external_tool' || params[:type] == 'lti/message_handler'
when 'context_external_tool', 'external_tool', 'lti/message_handler'
title = params[:title]
added_item ||= self.content_tags.build(:context => self.context)
@ -706,7 +709,7 @@ class ContextModule < ActiveRecord::Base
end
added_item.save
added_item
elsif params[:type] == 'context_module_sub_header' || params[:type] == 'sub_header'
when 'context_module_sub_header', 'sub_header'
title = params[:title]
added_item ||= self.content_tags.build(:context => self.context)
added_item.attributes = {

View File

@ -3943,10 +3943,11 @@ class Course < ActiveRecord::Base
def apply_visibility_configuration(course_visibility, syllabus_visibility)
apply_overridden_course_visibility(course_visibility)
if course_visibility == 'institution'
case course_visibility
when 'institution'
self.is_public_to_auth_users = true
self.is_public = false
elsif course_visibility == 'public'
when 'public'
self.is_public = true
else
self.is_public_to_auth_users = false

View File

@ -1611,9 +1611,10 @@ class DiscussionTopic < ActiveRecord::Base
item = RSS::Rss::Channel::Item.new
item.title = before_label((asset.title rescue "")) + elem.name
link = nil
if asset.is_a?(DiscussionTopic)
case asset
when DiscussionTopic
link = "http://#{HostUrl.context_host(asset.context)}/#{asset.context_url_prefix}/discussion_topics/#{asset.id}"
elsif asset.is_a?(DiscussionEntry)
when DiscussionEntry
link = "http://#{HostUrl.context_host(asset.context)}/#{asset.context_url_prefix}/discussion_topics/#{asset.discussion_topic_id}#entry-#{asset.id}"
end
@ -1622,12 +1623,13 @@ class DiscussionTopic < ActiveRecord::Base
item.pubDate = elem.updated_at.utc
item.description = asset ? asset.message : elem.name
item.enclosure
if elem.is_a?(Attachment)
case elem
when Attachment
item.guid.content = link + "/#{elem.uuid}"
url = "http://#{HostUrl.context_host(elem.context)}/#{elem.context_url_prefix}"\
"/files/#{elem.id}/download#{elem.extension}?verifier=#{elem.uuid}"
item.enclosure = RSS::Rss::Channel::Item::Enclosure.new(url, elem.size, elem.content_type)
elsif elem.is_a?(MediaObject)
when MediaObject
item.guid.content = link + "/#{elem.media_id}"
details = elem.podcast_format_details
content_type = 'video/mpeg'

View File

@ -104,18 +104,19 @@ class EportfolioEntry < ActiveRecord::Base
cnt.times do |idx|
obj = params[("section_" + (idx + 1).to_s).to_sym].slice(:section_type, :content, :submission_id, :attachment_id)
new_obj = { :section_type => obj[:section_type] }
if obj[:section_type] == 'rich_text' || obj[:section_type] == 'html'
case obj[:section_type]
when 'rich_text', 'html'
config = CanvasSanitize::SANITIZE
new_obj[:content] = Sanitize.clean(obj[:content] || '', config).strip
new_obj = nil if new_obj[:content].empty?
elsif obj[:section_type] == 'submission'
when 'submission'
submission = eportfolio.user.submissions.where(id: obj[:submission_id]).exists? if obj[:submission_id].present?
if submission
new_obj[:submission_id] = obj[:submission_id].to_i
else
new_obj = nil
end
elsif obj[:section_type] == 'attachment'
when 'attachment'
attachment = eportfolio.user.attachments.active.where(id: obj[:attachment_id]).exists? if obj[:attachment_id].present?
if attachment
new_obj[:attachment_id] = obj[:attachment_id].to_i
@ -171,9 +172,10 @@ class EportfolioEntry < ActiveRecord::Base
return if content_regexp.blank?
content_bodies = content_sections.map do |section|
if section.is_a?(String)
case section
when String
section
elsif section.is_a?(Hash)
when Hash
section[:content]
end
end

View File

@ -86,9 +86,10 @@ class ExternalFeed < ActiveRecord::Base
def format_description(desc)
desc = (desc || "").to_s
if self.verbosity == 'link_only'
case self.verbosity
when 'link_only'
""
elsif self.verbosity == 'truncate'
when 'truncate'
self.extend TextHelper
truncate_html(desc, :max_length => 250)
else
@ -97,7 +98,8 @@ class ExternalFeed < ActiveRecord::Base
end
def add_entry(item, feed, feed_type)
if feed_type == :rss
case feed_type
when :rss
uuid = item.respond_to?(:guid) && item.guid && item.guid.content.to_s
if uuid && uuid.length > 255
uuid = Digest::SHA256.hexdigest(uuid)
@ -136,7 +138,7 @@ class ExternalFeed < ActiveRecord::Base
:uuid => uuid
)
return entry if entry.save
elsif feed_type == :atom
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

View File

@ -290,11 +290,12 @@ class Folder < ActiveRecord::Base
dup.save!
self.subcontent.each do |item|
if options[:everything] || options[:all_files] || options[item.asset_string.to_sym]
if item.is_a?(Attachment)
case item
when Attachment
file = item.clone_for(context, nil, options.slice(:overwrite, :force_copy))
file.folder_id = dup.id
file.save_without_broadcasting!
elsif item.is_a?(Folder)
when Folder
sub = item.clone_for(context, nil, options)
sub.parent_folder_id = dup.id
sub.save!
@ -312,9 +313,10 @@ class Folder < ActiveRecord::Base
end
def self.root_folder_name_for_context(context)
if context.is_a? Course
case context
when Course
ROOT_FOLDER_NAME
elsif context.is_a? User
when User
MY_FILES_FOLDER_NAME
else
"files"

View File

@ -638,9 +638,10 @@ class Group < ActiveRecord::Base
return true if can_participate
return false unless user.present? && self.context.present?
return true if self.group_category.try(:communities?)
if self.context.is_a?(Course)
case self.context
when Course
return self.context.enrollments.not_fake.where(:user_id => user.id).active_by_date.exists?
elsif self.context.is_a?(Account)
when Account
return self.context.root_account.user_account_associations.where(:user_id => user.id).exists?
end

View File

@ -91,9 +91,10 @@ module Importers
rules = ""
if hash[:rules] && hash[:rules].length > 0
hash[:rules].each do |rule|
if rule[:drop_type] == "drop_lowest" || rule[:drop_type] == "drop_highest"
case rule[:drop_type]
when "drop_lowest", "drop_highest"
rules += "#{rule[:drop_type]}:#{rule[:drop_count]}\n"
elsif rule[:drop_type] == "never_drop"
when "never_drop"
if context.respond_to?(:assignment_group_no_drop_assignments)
context.assignment_group_no_drop_assignments[rule[:assignment_migration_id]] = item
end

View File

@ -178,14 +178,15 @@ module Importers
elsif (grading = hash[:grading])
hash[:due_at] ||= grading[:due_at] || grading[:due_date]
hash[:assignment_group_migration_id] ||= grading[:assignment_group_migration_id]
if /numeric|points/i.match?(grading[:grade_type])
case grading[:grade_type]
when /numeric|points/i
item.points_possible = grading[:points_possible] ? grading[:points_possible].to_f : 10
elsif /alphanumeric|letter_grade/i.match?(grading[:grade_type])
when /alphanumeric|letter_grade/i
item.grading_type = "letter_grade"
item.points_possible = grading[:points_possible] ? grading[:points_possible].to_f : 100
elsif grading[:grade_type] == 'rubric'
when 'rubric'
hash[:rubric_migration_id] ||= grading[:rubric_id]
elsif grading[:grade_type] == 'not_graded'
when 'not_graded'
item.submission_types = 'not_graded'
end
end

View File

@ -39,9 +39,10 @@ module Importers
bank_context = nil
unless migration.cross_institution?
if hash[:question_bank_context] =~ /account_(\d*)/
case hash[:question_bank_context]
when /account_(\d*)/
bank_context = Account.where(id: $1).first
elsif hash[:question_bank_context] =~ /course_(\d*)/
when /course_(\d*)/
bank_context = Course.where(id: $1).first
end

View File

@ -861,7 +861,8 @@ class Quizzes::Quiz < ActiveRecord::Base
end
def hide_results=(val)
if val.is_a?(Hash)
case val
when Hash
val = if val[:last_attempt] == '1'
'until_after_last_attempt'
elsif val[:never] != '1'
@ -869,7 +870,7 @@ class Quizzes::Quiz < ActiveRecord::Base
else
nil
end
elsif val == ""
when ""
val = nil
end
write_attribute(:hide_results, val)

View File

@ -99,9 +99,10 @@ class Quizzes::QuizQuestion < ActiveRecord::Base
# The user/teacher who's performing the regrade (e.g, updating the question).
# Note that this is NOT an id, but an actual instance of a User model.
def question_data=(in_data)
data = if in_data.is_a?(String)
data = case in_data
when String
ActiveSupport::JSON.decode(in_data)
elsif in_data.is_a?(Hash)
when Hash
in_data.with_indifferent_access
else
in_data

View File

@ -33,10 +33,11 @@ module Quizzes::QuizQuestion::AnswerParsers
a[:numerical_answer_type] = fields.fetch_any(:numerical_answer_type)
if a[:numerical_answer_type] == "exact_answer"
case a[:numerical_answer_type]
when "exact_answer"
a[:exact] = fields.fetch_any(:answer_exact).to_f
a[:margin] = fields.fetch_any(:answer_error_margin).to_f
elsif a[:numerical_answer_type] == "precision_answer"
when "precision_answer"
a[:approximate] = fields.fetch_any(:answer_approximate).to_f
a[:precision] = fields.fetch_any(:answer_precision).to_i
else

View File

@ -66,7 +66,8 @@ class Quizzes::QuizQuestion::NumericalQuestion < Quizzes::QuizQuestion::Base
answer_number = i18n_decimal(answer_text)
match = answers.find do |answer|
if answer[:numerical_answer_type] == "exact_answer"
case answer[:numerical_answer_type]
when "exact_answer"
val = BigDecimal(answer[:exact].to_s.presence || '0.0')
# calculate margin value using percentage
@ -78,7 +79,7 @@ class Quizzes::QuizQuestion::NumericalQuestion < Quizzes::QuizQuestion::Base
min = val - margin
max = val + margin
answer_number >= min && answer_number <= max
elsif answer[:numerical_answer_type] == "precision_answer"
when "precision_answer"
submission = answer_number.split
expected = BigDecimal(answer[:approximate].to_s.presence || '0.0').split
precision = answer[:precision].to_i
@ -107,9 +108,10 @@ class Quizzes::QuizQuestion::NumericalQuestion < Quizzes::QuizQuestion::Base
super
@question_data.answers.each do |answer|
answer[:text] = if answer[:numerical_answer_type] == 'exact_answer'
answer[:text] = case answer[:numerical_answer_type]
when 'exact_answer'
I18n.t("%{exact_value} +/- %{margin}", :exact_value => answer[:exact], :margin => answer[:margin])
elsif answer[:numerical_answer_type] == 'precision_answer'
when 'precision_answer'
I18n.t("%{approximate_value} with precision %{precision}", :approximate_value => answer[:approximate], :precision => answer[:precision])
else
I18n.t("%{lower_bound} to %{upper_bound}", :lower_bound => answer[:start], :upper_bound => answer[:end])

View File

@ -278,16 +278,17 @@ class Quizzes::QuizStatistics::StudentAnalysis < Quizzes::QuizStatistics::Report
strip_html_answers(question)
answer_item = question && question[:answers]&.detect { |a| a[:id] == answer[:answer_id] }
answer_item ||= answer
if question[:question_type] == 'fill_in_multiple_blanks_question'
case question[:question_type]
when 'fill_in_multiple_blanks_question'
blank_ids = question[:answers].map { |a| a[:blank_id] }.uniq
row << blank_ids.map { |blank_id| answer["answer_for_#{blank_id}".to_sym].try(:gsub, /,/, '\,') }.compact.join(',')
elsif question[:question_type] == 'multiple_answers_question'
when 'multiple_answers_question'
row << question[:answers].map { |a| answer["answer_#{a[:id]}".to_sym] == '1' ? a[:text].gsub(/,/, '\,') : nil }.compact.join(',')
elsif question[:question_type] == 'multiple_dropdowns_question'
when 'multiple_dropdowns_question'
blank_ids = question[:answers].map { |a| a[:blank_id] }.uniq
answer_ids = blank_ids.map { |blank_id| answer["answer_for_#{blank_id}".to_sym] }
row << answer_ids.map { |answer_id| (question[:answers].detect { |a| a[:id] == answer_id } || {})[:text].try(:gsub, /,/, '\,') }.compact.join(',')
elsif question[:question_type] == 'calculated_question'
when 'calculated_question'
list = question[:answers].take(1).flat_map do |ans|
ans[:variables] && ans[:variables].map do |variable|
[variable[:name], variable[:value].to_s].map { |str| str.gsub(/=>/, '\=>') }.join('=>')
@ -295,7 +296,7 @@ class Quizzes::QuizStatistics::StudentAnalysis < Quizzes::QuizStatistics::Report
end
list << answer[:text]
row << list.map { |str| (str || '').gsub(/,/, '\,') }.join(',')
elsif question[:question_type] == 'matching_question'
when 'matching_question'
answer_ids = question[:answers].map { |a| a[:id] }
answer_and_matches = answer_ids.map { |aid| [aid, answer["answer_#{aid}".to_sym].to_i] }
row << answer_and_matches.map do |answer_id, match_id|
@ -305,9 +306,9 @@ class Quizzes::QuizStatistics::StudentAnalysis < Quizzes::QuizStatistics::Report
res << (match[:right] || match[:text])
res.map { |s| (s || '').gsub(/=>/, '\=>') }.join('=>').gsub(/,/, '\,')
end.join(',')
elsif question[:question_type] == 'numerical_question'
when 'numerical_question'
row << (answer && answer[:text])
elsif question[:question_type] == 'file_upload_question'
when 'file_upload_question'
row << attachment_csv(answer)
else

View File

@ -304,9 +304,10 @@ class Quizzes::QuizSubmissionService
unless can_take.eligible?
reason = can_take.declined_reason_renders
if reason == :access_code
case reason
when :access_code
reject! 'invalid access code', 403
elsif reason == :invalid_ip
when :invalid_ip
reject! 'IP address denied', 403
end
reject! 'quiz is locked', 400

View File

@ -1818,9 +1818,10 @@ class RoleOverride < ActiveRecord::Base
# override.enabled.nil? is no longer possible, but is important for the migration that removes nils
if override.new_record? || override.enabled.nil?
if last_override
if generated_permission[:enabled] == [:descendants]
case generated_permission[:enabled]
when [:descendants]
generated_permission[:enabled] = [:self, :descendants]
elsif generated_permission[:enabled] == [:self]
when [:self]
generated_permission[:enabled] = nil
end
end

View File

@ -334,14 +334,15 @@ module SpeedGrader
provisional_grades = provisional_grades.preload(:scorer)
end
if grading_role == :provisional_grader
case grading_role
when :provisional_grader
provisional_grades = if grader_comments_hidden?(current_user: current_user, assignment: assignment)
provisional_grades.not_final.where(scorer: current_user)
else
select_fields = ModeratedGrading::GRADE_ATTRIBUTES_ONLY.dup.push(:id, :submission_id)
provisional_grades.select(select_fields)
end
elsif grading_role == :grader
when :grader
provisional_grades = ModeratedGrading::ProvisionalGrade.none
end
provisional_grades.order(:id).to_a.group_by(&:submission_id)

View File

@ -823,9 +823,10 @@ class Submission < ActiveRecord::Base
end
def turnitin_assets
if self.submission_type == 'online_upload'
case self.submission_type
when 'online_upload'
self.attachments.select(&:turnitinable?)
elsif self.submission_type == 'online_text_entry'
when 'online_text_entry'
[self]
else
[]
@ -1134,9 +1135,10 @@ class Submission < ActiveRecord::Base
end
def vericite_assets
if self.submission_type == 'online_upload'
case self.submission_type
when 'online_upload'
self.attachments.select(&:vericiteable?)
elsif self.submission_type == 'online_text_entry'
when 'online_text_entry'
[self]
else
[]

View File

@ -228,9 +228,10 @@ class UserService < ActiveRecord::Base
end
def self.service_type(type)
if type == 'google_docs' || type == 'google_drive'
case type
when 'google_docs', 'google_drive'
'DocumentService'
elsif type == 'delicious' || type == 'diigo'
when 'delicious', 'diigo'
'BookmarkService'
else
'UserService'

View File

@ -41,12 +41,13 @@ module ArbitraryStrongishParams
slice(*filter.keys).each do |key, value|
next unless value
if filter[key] == ActionController::Parameters::EMPTY_ARRAY
case filter[key]
when ActionController::Parameters::EMPTY_ARRAY
# Declaration { comment_ids: [] }.
array_of_permitted_scalars?(self[key]) do |val|
params[key] = val
end
elsif filter[key] == ANYTHING
when ANYTHING
if (filtered = recursive_arbitrary_filter(value))
params[key] = filtered
params.instance_variable_get(:@anythings)[key] = true

View File

@ -59,9 +59,10 @@ module Audits
def configured?
strategy = backend_strategy
if strategy == :cassandra
case strategy
when :cassandra
return CanvasCassandra::DatabaseBuilder.configured?('auditors')
elsif strategy == :active_record
when :active_record
return Rails.configuration.database_configuration[Rails.env].present?
end

View File

@ -265,10 +265,11 @@ module CanvasCache
host: location,
}
unless NON_KEY_COMMANDS.include?(command)
message[:key] = if command == :mset
message[:key] = case command
when :mset
# This is an array with a single element: an array alternating key/values
request.first(&:first).select.with_index { |_, i| i % 2 == 0 }
elsif command == :mget
when :mget
request
else
request.first

View File

@ -41,10 +41,11 @@ module CanvasPartman::Concerns
def partitioning_strategy=(value)
raise ArgumentError unless [:by_date, :by_id].include?(value)
if value == :by_date
case value
when :by_date
self.partitioning_field = "created_at"
self.partitioning_interval = :months
elsif value == :by_id
when :by_id
self.partitioning_field = nil
self.partition_size = 1_000_000
end

View File

@ -127,13 +127,14 @@ class CanvasUnzip
mime_type = 'application/x-tar' # it may not actually be a tar though, so rescue if there's a problem
end
if mime_type == 'application/zip'
case mime_type
when 'application/zip'
Zip::File.open(file) do |zipfile|
zipfile.entries.each_with_index do |zip_entry, index|
yield(Entry.new(zip_entry), index)
end
end
elsif mime_type == 'application/x-tar'
when 'application/x-tar'
index = 0
begin
Gem::Package::TarReader.new(file).each do |tar_entry|
@ -160,9 +161,10 @@ class CanvasUnzip
attr_reader :entry, :type
def initialize(entry)
if entry.is_a?(Zip::Entry)
case entry
when Zip::Entry
@type = :zip
elsif entry.is_a?(Gem::Package::TarReader::Entry)
when Gem::Package::TarReader::Entry
@type = :tar
end
@ -172,9 +174,10 @@ class CanvasUnzip
end
def symlink?
if type == :zip
case type
when :zip
entry.symlink?
elsif type == :tar
when :tar
entry.header.typeflag == "2"
end
end
@ -188,19 +191,21 @@ class CanvasUnzip
end
def name
@name ||= if type == :zip
@name ||= case type
when :zip
# the standard is DOS (cp437) or UTF-8, although in practice, anything goes
normalize_name(entry.name, 'cp437')
elsif type == :tar
when :tar
# there is no standard. this seems like a reasonable fallback to me
normalize_name(entry.full_name.sub(/^\.\//, ''), 'iso-8859-1')
end
end
def size
if type == :zip
case type
when :zip
entry.size
elsif type == :tar
when :tar
entry.header.size
end
end
@ -218,7 +223,8 @@ class CanvasUnzip
digest = Digest::MD5.new
::File.open(dest_path, "wb") do |os|
if type == :zip
case type
when :zip
entry.get_input_stream do |is|
entry.set_extra_attributes_on_path(dest_path)
buf = +''
@ -228,7 +234,7 @@ class CanvasUnzip
yield(buf.size) if block_given?
end
end
elsif type == :tar
when :tar
while (buf = entry.read(BUFFER_SIZE))
os << buf
digest.update(buf)

View File

@ -53,11 +53,12 @@ module EventStream::Backend
def fetch(ids, strategy: :batch)
rows = []
if available? && ids.present?
if strategy == :batch
case strategy
when :batch
database.execute(fetch_cql, ids, consistency: read_consistency_level).fetch do |row|
rows << record_type.from_attributes(row.to_hash)
end
elsif strategy == :serial
when :serial
ids.each do |record_id|
database.execute(fetch_one_cql, record_id, consistency: read_consistency_level).fetch do |row|
rows << record_type.from_attributes(row.to_hash)

View File

@ -53,9 +53,10 @@ class EventStream::Index
end
def strategy_for(strategy_name)
if strategy_name == :active_record
case strategy_name
when :active_record
@_ar_decorator ||= EventStream::IndexStrategy::ActiveRecord.new(self)
elsif strategy_name == :cassandra
when :cassandra
@_cass_decorator ||= EventStream::IndexStrategy::Cassandra.new(self)
else
raise "Unknown Indexing Strategy: #{strategy_name}"

View File

@ -77,7 +77,8 @@ module GoogleDrive
result = client_execute(:uri => @uri)
if result.status == 200
case result.status
when 200
file_name = file['title']
name_extension = file_name[/\.([a-z]+$)/, 1]
file_extension = name_extension || file_extension_from_header(result.headers, entry)
@ -86,7 +87,7 @@ module GoogleDrive
file_name += ".#{file_extension}" unless name_extension
content_type = result.headers['Content-Type'].sub(/; charset=[^;]+/, '')
return [result, file_name, file_extension, content_type]
elsif result.status == 307
when 307
@uri = result.response['Location']
redirect_limit -= 1
else

View File

@ -167,7 +167,8 @@ namespace :i18n do
task :generate_lolz => [:generate, :environment] do
strings_processed = 0
process_lolz = Proc.new do |val|
if val.is_a?(Hash)
case val
when Hash
processed = strings_processed
hash = Hash.new
@ -175,9 +176,9 @@ namespace :i18n do
print '.' if strings_processed > processed
hash
elsif val.is_a?(Array)
when Array
val.each.map { |v| process_lolz.call(v) }
elsif val.is_a?(String)
when String
strings_processed += 1
I18n.let_there_be_lols(val)
else

View File

@ -95,11 +95,12 @@ module LtiOutbound
hash['custom_canvas_user_id'] = '$Canvas.user.id'
hash['lis_person_sourcedid'] = '$Person.sourcedId' if user.sis_source_id
hash['custom_canvas_user_login_id'] = '$Canvas.user.loginId'
if context.is_a?(LTICourse)
case context
when LTICourse
hash['custom_canvas_course_id'] = '$Canvas.course.id'
hash['custom_canvas_workflow_state'] = '$Canvas.course.workflowState'
hash['lis_course_offering_sourcedid'] = '$CourseSection.sourcedId' if context.sis_source_id
elsif context.is_a?(LTIAccount) || context.is_a?(LTIUser)
when LTIAccount, LTIUser
hash['custom_canvas_account_id'] = '$Canvas.account.id'
hash['custom_canvas_account_sis_id'] = '$Canvas.account.sisSourceId'
end
@ -155,20 +156,21 @@ module LtiOutbound
end
def set_resource_type_keys
if resource_type == 'editor_button'
case resource_type
when 'editor_button'
hash['selection_directive'] = 'embed_content' # backwards compatibility
hash['ext_content_intended_use'] = 'embed'
hash['ext_content_return_types'] = 'oembed,lti_launch_url,url,image_url,iframe'
hash['ext_content_return_url'] = return_url
elsif resource_type == 'resource_selection'
when 'resource_selection'
hash['selection_directive'] = 'select_link' # backwards compatibility
hash['ext_content_intended_use'] = 'navigation'
hash['ext_content_return_types'] = 'lti_launch_url'
hash['ext_content_return_url'] = return_url
elsif resource_type == 'homework_submission'
when 'homework_submission'
hash['ext_content_intended_use'] = 'homework'
hash['ext_content_return_url'] = return_url
elsif resource_type == 'migration_selection'
when 'migration_selection'
hash['ext_content_intended_use'] = 'content_package'
hash['ext_content_return_types'] = 'file'
hash['ext_content_file_extensions'] = 'zip,imscc'

View File

@ -51,9 +51,10 @@ module AccountReports
:files => files
))
if @reports.length == 0
case @reports.length
when 0
send_report()
elsif @reports.length == 1
when 1
csv = self.send(@reports.first)
send_report(csv)
else

View File

@ -145,11 +145,12 @@ module Qti
def self.parse_time_limit(time_limit)
time_indicator = time_limit[0..0].downcase if time_limit.length > 0
if time_indicator == 'd'
case time_indicator
when 'd'
24 * 60 * time_limit[1..].to_i
elsif time_indicator == 'h'
when 'h'
60 * time_limit[1..].to_i
elsif time_indicator == 'm'
when 'm'
time_limit[1..].to_i
else
# instructure uses minutes, QTI uses seconds
@ -204,9 +205,10 @@ module Qti
end
section.children.each do |child|
if child.name == "assessmentSection"
case child.name
when "assessmentSection"
process_section(child)
elsif child.name == "assessmentItemRef"
when "assessmentItemRef"
process_question(child, questions_list)
end
end

View File

@ -262,15 +262,16 @@ module Qti
def get_base_value(node)
weight = AssessmentItemConverter::DEFAULT_INCORRECT_WEIGHT
if node['baseType'] == "float" # base_value = node.at_css('baseValue[baseType=float]')
case node['baseType']
when "float" # base_value = node.at_css('baseValue[baseType=float]')
if node.text =~ /score\.max/i or node.text.to_f > 0
weight = AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT
end
elsif node['baseType'] == "integer" # elsif base_value = node.at_css('baseValue[baseType=integer]')
when "integer" # elsif base_value = node.at_css('baseValue[baseType=integer]')
if node.text.to_i > 0
weight = AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT
end
elsif node['baseType'] == "boolean" # elsif base_value = node.at_css('baseValue[baseType=boolean]')
when "boolean" # elsif base_value = node.at_css('baseValue[baseType=boolean]')
if node.text.downcase == "true"
weight = AssessmentItemConverter::DEFAULT_CORRECT_WEIGHT
end

View File

@ -127,7 +127,8 @@ module Qti
def recursively_clean_inline_body_and_get_answers(node, answer_hash)
node.children.each do |child|
if child.name == 'inlineChoiceInteraction'
case child.name
when 'inlineChoiceInteraction'
response_id = child['responseIdentifier']
answer_hash[response_id] = {}
child.search('inlineChoice').each do |choice|
@ -141,7 +142,7 @@ module Qti
answer_hash[response_id][choice_id] = answer
end
child.replace(Nokogiri::XML::Text.new("[#{response_id}]", @doc))
elsif child.name == 'text'
when 'text'
child.content = child.text.gsub(']]>', '').gsub('<div></div>', '')
else
recursively_clean_inline_body_and_get_answers(child, answer_hash)
@ -156,9 +157,10 @@ module Qti
next if node.name == 'text'
text = ''
if node.name == 'div'
case node.name
when 'div'
text = sanitize_html_string(node.text, true)
elsif node.name == 'extendedTextInteraction'
when 'extendedTextInteraction'
id = node['responseIdentifier']
text = " [#{id}] "
end

View File

@ -167,15 +167,16 @@ module Api
return lookups['id'], id if id.is_a?(Numeric) || id.is_a?(ActiveRecord::Base)
id = id.to_s.strip
if id =~ %r{\Ahex:(lti_[\w_]+|sis_[\w_]+):(([0-9A-Fa-f]{2})+)\z}
case id
when %r{\Ahex:(lti_[\w_]+|sis_[\w_]+):(([0-9A-Fa-f]{2})+)\z}
sis_column = $1
sis_id = [$2].pack('H*')
elsif id =~ %r{\A(lti_[\w_]+|sis_[\w_]+):(.+)\z}
when %r{\A(lti_[\w_]+|sis_[\w_]+):(.+)\z}
sis_column = $1
sis_id = $2
elsif ID_REGEX.match?(id)
when ID_REGEX
return lookups['id'], (/\A\d+\z/.match?(id) ? id.to_i : id)
elsif id =~ UUID_REGEX
when UUID_REGEX
return lookups['uuid'], $1
else
return nil, nil

View File

@ -1049,9 +1049,10 @@ module Api::V1::Assignment
def assignment_configuration_tool(assignment_params)
tool_id = assignment_params['similarityDetectionTool'].split('_').last.to_i
tool = nil
if assignment_params['configuration_tool_type'] == 'ContextExternalTool'
case assignment_params['configuration_tool_type']
when 'ContextExternalTool'
tool = ContextExternalTool.find_external_tool_by_id(tool_id, context)
elsif assignment_params['configuration_tool_type'] == 'Lti::MessageHandler'
when 'Lti::MessageHandler'
mh = Lti::MessageHandler.find(tool_id)
mh_context = mh.resource_handler.tool_proxy.context
tool = mh if mh_context == @context || @context.account_chain.include?(mh_context)

View File

@ -107,9 +107,10 @@ module Api::V1::CalendarEvent
hash['hidden'] = user ? event.hidden? : false
if include.include?('participants')
if event.context_type == 'User'
case event.context_type
when 'User'
hash['user'] = user_json(event.context, user, session)
elsif event.context_type == 'Group'
when 'Group'
hash['group'] = group_json(event.context, user, session, :include => ['users'])
end
end

View File

@ -59,9 +59,10 @@ module Api::V1::ExternalTools
end
def tool_pagination_url
if @context.is_a? Course
case @context
when Course
api_v1_course_external_tools_url(@context)
elsif @context.is_a? Group
when Group
api_v1_group_external_tools_url(@context)
else
api_v1_account_external_tools_url(@context)

View File

@ -190,11 +190,12 @@ module Canvas::Migration
end
a[:questions].each do |q|
if q[:question_type] == "question_reference"
case q[:question_type]
when "question_reference"
if should_prepend?(:assessment_questions, q[:migration_id], existing_ids)
q[:migration_id] = prepend_id(q[:migration_id], prepend_value)
end
elsif q[:question_type] == "question_group"
when "question_group"
if q[:question_bank_migration_id].present? && should_prepend?(:assessment_question_banks, q[:question_bank_migration_id], existing_ids)
q[:question_bank_migration_id] = prepend_id(q[:question_bank_migration_id], prepend_value)
end

View File

@ -152,11 +152,12 @@ module CC::Importer
node.children.each do |property|
next if property.name == 'text'
if property.name == 'property'
case property.name
when 'property'
props[property['name']] = property.text.strip
elsif property.name == 'options'
when 'options'
props[property['name']] = get_custom_properties(property)
elsif property.name == 'custom'
when 'custom'
props[:custom_fields] = get_custom_properties(property)
end
end

View File

@ -31,9 +31,10 @@ module CC::Importer::Canvas
return list unless node
node.children.each do |child|
if child.name == 'learningOutcome'
case child.name
when 'learningOutcome'
list << process_learning_outcome(child)
elsif child.name == 'learningOutcomeGroup'
when 'learningOutcomeGroup'
list << process_outcome_group(child)
end
end

View File

@ -63,7 +63,8 @@ module CC
unless ct.content_type == 'ContextModuleSubHeader'
attributes[:identifierref] = create_key(ct.content)
end
if ct.content_type == 'ExternalUrl'
case ct.content_type
when 'ExternalUrl'
# Need to create web link objects in the resources
link = {
:migration_id => create_key(ct, 'weblink'),
@ -72,7 +73,7 @@ module CC
}
@manifest.weblinks << link
attributes[:identifierref] = link[:migration_id]
elsif ct.content_type == 'ContextExternalTool'
when 'ContextExternalTool'
attributes[:identifierref] = attributes[:identifier]
attributes[:identifier] = create_key(ct, "module_item")
end

View File

@ -417,10 +417,11 @@ class ContentZipper
end
def add_text_or_url(type, to_zip, called)
if type == :text
case type
when :text
filename = "#{called}_text.html"
display_page = "text_entry_page.html.erb"
elsif type == :url
when :url
filename = "#{called}_link.html"
display_page = "redirect_page.html.erb"
end

View File

@ -39,11 +39,12 @@ module DataFixup::GranularPermissions::AddRoleOverridesForManageCoursesAdd
role_context = role.built_in? ? root_account : role.account
scope = root_account.enrollments.active
if base_role_types == %w[TeacherEnrollment DesignerEnrollment]
case base_role_types
when %w[TeacherEnrollment DesignerEnrollment]
if root_account.teachers_can_create_courses? && scope.where(type: base_role_types).exists?
create_role_override(role, role_context)
end
elsif base_role_types == %w[StudentEnrollment ObserverEnrollment]
when %w[StudentEnrollment ObserverEnrollment]
if root_account.students_can_create_courses? && scope.where(type: base_role_types).exists?
create_role_override(role, role_context)
end

View File

@ -38,11 +38,12 @@ module DumpHelper
if val.is_a?(Hash)
find_dump_error(val.keys, "#{key}.keys", visited_dump_vars)
end
if val.is_a?(Hash) || val.is_a?(Struct)
case val
when Hash, Struct
val.each_pair do |k, v|
find_dump_error(v, "#{key}[#{k.inspect}]", visited_dump_vars)
end
elsif val.is_a?(Array)
when Array
val.each_with_index do |v, i|
find_dump_error(v, "#{key}[#{i}]", visited_dump_vars)
end

View File

@ -208,15 +208,16 @@ class Feature
def self.applicable_features(object, type: nil)
applicable_types = []
if object.is_a?(Account)
case object
when Account
applicable_types << 'Account'
applicable_types << 'Course'
applicable_types << 'RootAccount' if object.root_account?
applicable_types << 'User' if object.site_admin?
applicable_types << 'SiteAdmin' if object.site_admin?
elsif object.is_a?(Course)
when Course
applicable_types << 'Course'
elsif object.is_a?(User)
when User
applicable_types << 'User'
end
definitions.values.select { |fd| applicable_types.include?(fd.applies_to) && (type.nil? || fd.type == type) }

View File

@ -27,13 +27,15 @@ module FeatureFlags
# This is a "one-way" flag:
# - Once Allowed, it can no longer be set to Off.
# - Once On, it can no longer be Off nor Allowed.
if context.is_a?(Course)
case context
when Course
transitions['off']['locked'] = true if from_state == 'on' # lock off to enforce no take backs
elsif context.is_a?(Account)
when Account
transitions['allowed'] ||= {}
if from_state == 'allowed'
case from_state
when 'allowed'
transitions['off']['locked'] = true # lock off to enforce no take backs
elsif from_state == 'on'
when 'on'
# lock both `off` and `allowed` to enforce no take backs
transitions['off']['locked'] = true
transitions['allowed']['locked'] = true

View File

@ -29,9 +29,10 @@ module FeatureFlags
def self.wrap_translate_text(value)
return -> { "" } if value.empty?
if value.is_a?(String)
case value
when String
-> { I18n.send(:t, value) }
elsif value.is_a?(Hash)
when Hash
wrapper = value.delete(:wrapper)
keys = value.keys
raise "invalid i18n settings while translating: #{value}" if keys.size != 1

View File

@ -33,15 +33,16 @@ class GradebookUserIds
end
def user_ids
if @column == "student"
case @column
when "student"
sort_by_student_field
elsif /assignment_\d+$/.match?(@column)
when /assignment_\d+$/
assignment_id = @column[/\d+$/]
send("sort_by_assignment_#{@sort_by}", assignment_id)
elsif /^assignment_group_\d+$/.match?(@column)
when /^assignment_group_\d+$/
assignment_id = @column[/\d+$/]
sort_by_assignment_group(assignment_id)
elsif @column == "total_grade"
when "total_grade"
sort_by_total_grade
else
sort_by_student_name
@ -190,9 +191,10 @@ class GradebookUserIds
end
def sort_by_scores(type = :total_grade, id = nil)
score_scope = if type == :assignment_group
score_scope = case type
when :assignment_group
"scores.assignment_group_id=#{Score.connection.quote(id)}"
elsif type == :grading_period
when :grading_period
"scores.grading_period_id=#{Score.connection.quote(id)}"
else
"scores.course_score IS TRUE"

View File

@ -528,9 +528,10 @@ class MessageableUser
discussion = discussion_or_id.is_a?(DiscussionTopic) ? discussion_or_id : DiscussionTopic.where(id: discussion_or_id).first
context = discussion.address_book_context_for(@user)
if context.is_a?(Course)
case context
when Course
messageable_users_in_course_scope(context, nil, options)
elsif context.is_a?(Group)
when Group
messageable_users_in_group_scope(context, options)
else
messageable_users_in_section_scope(context, nil, options)

View File

@ -60,7 +60,8 @@ class OpenObject < OpenStruct
new_list
elsif pre
pre.each do |name, value|
if value.is_a? Array
case value
when Array
new_list = []
value.each do |obj|
new_list << if obj.is_a? Hash
@ -70,7 +71,7 @@ class OpenObject < OpenStruct
end
end
pre[name] = new_list
elsif value.is_a? Hash
when Hash
pre[name] = OpenObject.process(value)
end
end

View File

@ -54,9 +54,10 @@ module Outcomes
check_object(object)
type = object[:object_type]
if type == 'outcome'
case type
when 'outcome'
import_outcome(object)
elsif type == 'group'
when 'group'
import_group(object)
else
raise InvalidDataError, I18n.t(

View File

@ -128,9 +128,10 @@ module Plannable
# Grabs the value to use for the bookmark & comparison
def column_value(object, col)
if col.is_a?(Array)
case col
when Array
object.attributes.values_at(*col).compact.first # coalesce nulls
elsif col.is_a?(Hash)
when Hash
association_value(object, col)
else
object.attributes[col]

View File

@ -92,9 +92,10 @@ module SimpleTags
def self.normalize_tags(tags)
tags.inject([]) { |ary, tag|
if tag =~ /\A((course|group)_\d+).*/
case tag
when /\A((course|group)_\d+).*/
ary << $1
elsif tag =~ /\Asection_(\d+).*/
when /\Asection_(\d+).*/
section = CourseSection.where(id: $1).first
ary << section.course.asset_string if section
# TODO: allow user-defined tags, e.g. #foo

View File

@ -71,9 +71,10 @@ module SIS
course.short_name = short_name if short_name.present? && (course.new_record? || !course.stuck_sis_fields.include?(:short_name))
course.sis_source_id = abstract_course_id
if /active/i.match?(status)
case status
when /active/i
course.workflow_state = 'active'
elsif /deleted/i.match?(status)
when /deleted/i
course.workflow_state = 'deleted'
end

View File

@ -82,9 +82,10 @@ module SIS
account.sis_source_id = account_id
if status.present?
if /active/i.match?(status)
case status
when /active/i
account.workflow_state = 'active'
elsif /deleted/i.match?(status)
when /deleted/i
raise ImportError, "Cannot delete the sub_account with ID: #{account_id} because it has active sub accounts." if account.sub_accounts.active.exists?
raise ImportError, "Cannot delete the sub_account with ID: #{account_id} because it has active courses." if account.courses.active.exists?

View File

@ -91,10 +91,11 @@ module SIS
end
def create_or_find_admin(user, state)
if state == 'active'
case state
when 'active'
admin = @account.account_users.where(user: user, role: @role).first_or_initialize
admin.workflow_state = state
elsif state == 'deleted'
when 'deleted'
admin = @account.account_users.where(user: user, role: @role).where.not(sis_batch_id: nil).take
return unless admin

View File

@ -91,7 +91,8 @@ module SIS
@batch.data[:downloadable_attachment_ids] ||= []
@files.each do |file|
if File.file?(file)
if File.extname(file).downcase == '.zip'
case File.extname(file).downcase
when '.zip'
tmp_dir = Dir.mktmpdir
@tmp_dirs << tmp_dir
CanvasUnzip.extract_archive(file, tmp_dir)
@ -102,7 +103,7 @@ module SIS
att = create_batch_attachment(File.join(tmp_dir, file_name))
process_file(tmp_dir, file_name, att)
end
elsif File.extname(file).downcase == '.csv'
when '.csv'
att = @batch.attachment if @batch.attachment && File.extname(@batch.attachment.filename).downcase == '.csv'
att ||= create_batch_attachment file
process_file(File.dirname(file), File.basename(file), att)

View File

@ -230,15 +230,16 @@ module SIS
type = if role
role.base_role_type
else
if /\Ateacher\z/i.match?(enrollment_info.role)
case enrollment_info.role
when /\Ateacher\z/i
'TeacherEnrollment'
elsif /\Astudent/i.match?(enrollment_info.role)
when /\Astudent/i
'StudentEnrollment'
elsif /\Ata\z/i.match?(enrollment_info.role)
when /\Ata\z/i
'TaEnrollment'
elsif /\Aobserver\z/i.match?(enrollment_info.role)
when /\Aobserver\z/i
'ObserverEnrollment'
elsif /\Adesigner\z/i.match?(enrollment_info.role)
when /\Adesigner\z/i
'DesignerEnrollment'
end
end
@ -372,14 +373,15 @@ module SIS
all_done = false
return true if enrollment.workflow_state == 'deleted' && pseudo.workflow_state == 'deleted'
if /\Aactive/i.match?(enrollment_info.status)
case enrollment_info.status
when /\Aactive/i
message = set_enrollment_workflow_state(enrollment, enrollment_info, pseudo, user)
@messages << SisBatch.build_error(enrollment_info.csv, message, sis_batch: @batch, row: enrollment_info.lineno, row_info: enrollment_info.row_info) if message
elsif /\Acompleted/i.match?(enrollment_info.status)
when /\Acompleted/i
completed_status(enrollment)
elsif /\Ainactive/i.match?(enrollment_info.status)
when /\Ainactive/i
enrollment.workflow_state = 'inactive'
elsif /\Adeleted_last_completed/i.match?(enrollment_info.status)
when /\Adeleted_last_completed/i
# if any matching enrollment for the same user in the same course
# exists, we will mark the enrollment as deleted, but if it is the
# last enrollment it gets marked as completed
@ -388,7 +390,7 @@ module SIS
else
completed_status(enrollment)
end
elsif /\Adeleted/i.match?(enrollment_info.status)
when /\Adeleted/i
# we support creating deleted enrollments, but we want to preserve
# the state for roll_back_data so only set workflow_state for new
# objects otherwise delete them in a batch at the end unless it is

View File

@ -114,9 +114,10 @@ module SIS
end
section.integration_id = integration_id
if /active/i.match?(status)
case status
when /active/i
section.workflow_state = 'active'
elsif /deleted/i.match?(status)
when /deleted/i
section.workflow_state = 'deleted'
deleted_section_ids << section.id
end

View File

@ -56,9 +56,10 @@ module SIS
raise ImportError, "Invalid date_override_enrollment_type"
end
if /active/i.match?(status)
case status
when /active/i
term.set_overrides(@root_account, { date_override_enrollment_type => { :start_at => start_date, :end_at => end_date } })
elsif /deleted/i.match?(status)
when /deleted/i
term.enrollment_dates_overrides.where(enrollment_type: date_override_enrollment_type).destroy_all
end
else
@ -72,9 +73,10 @@ module SIS
term.integration_id = integration_id
if /active/i.match?(status)
case status
when /active/i
term.workflow_state = 'active'
elsif /deleted/i.match?(status)
when /deleted/i
term.workflow_state = 'deleted'
end
if (term.stuck_sis_fields & [:start_at, :end_at]).empty?

View File

@ -82,7 +82,8 @@ module SIS
end
unless section.stuck_sis_fields.include?(:course_id)
if /\Aactive\z/i.match?(status)
case status
when /\Aactive\z/i
if @course.deleted?
@course.workflow_state = 'claimed'
@ -103,7 +104,7 @@ module SIS
raise ImportError, "An active cross-listing failed: #{e}"
end
elsif /\Adeleted\z/i.match?(status)
when /\Adeleted\z/i
if @course && section.course_id != @course.id
@success_count += 1
return

View File

@ -19,10 +19,11 @@ module I18nliner
@translation_count += 1
@translations.line = name.to_s
value = definition[field]
if value.is_a?(String)
case value
when String
key = I18nliner::CallHelpers.infer_key(value)
@translations[key] = value
elsif value.is_a?(Hash)
when Hash
value.delete(:wrapper)
key = value.keys[0]
@translations[key.to_s] = value[key]

View File

@ -228,9 +228,10 @@ class UserMerge
value = from_record.value
if from_user.shard != target_user.shard
# tl;dr do the same thing as shard_aware_preferences
if key == "custom_colors"
case key
when "custom_colors"
value = Hash[value.map { |id, color| [translate_course_id_or_asset_string(id), color] }]
elsif key == "course_nicknames"
when "course_nicknames"
sub_key = translate_course_id_or_asset_string(sub_key)
end
end
@ -606,7 +607,8 @@ class UserMerge
model = table.to_s.classify.constantize
already_scope = model.where(:user_id => target_user)
scope = model.where(:user_id => from_user)
if model.name == "Submission"
case model.name
when "Submission"
# we prefer submissions that have grades then submissions that have
# a submission... that sort of makes sense.
# we swap empty objects in cases of collision so that we don't
@ -624,7 +626,7 @@ class UserMerge
merge_data.build_more_data(to_move, data: data) unless to_move.empty?
merge_data.build_more_data(move_back, data: data) unless move_back.empty?
swap_submission(model, move_back, table, to_move, to_move_ids, 'fk_rails_8d85741475')
elsif model.name == "Quizzes::QuizSubmission"
when "Quizzes::QuizSubmission"
subscope = already_scope.to_a
to_move = model.where(user_id: from_user).joins(:submission).where(submissions: { user_id: target_user }).to_a
move_back = model.where(user_id: target_user).joins(:submission).where(submissions: { user_id: from_user }).to_a

View File

@ -64,9 +64,10 @@ module UserSearch
enrollment_states = Array(options[:enrollment_state]) if options[:enrollment_state]
include_prior_enrollments = !options[:enrollment_state].nil?
include_inactive_enrollments = !!options[:include_inactive_enrollments]
if context.is_a?(Account)
case context
when Account
User.of_account(context).active
elsif context.is_a?(Course)
when Course
context.users_visible_to(searcher, include_prior_enrollments,
enrollment_state: enrollment_states, include_inactive: include_inactive_enrollments).distinct
else
@ -76,11 +77,12 @@ module UserSearch
def order_scope(users_scope, context, options = {})
order = ' DESC NULLS LAST, id DESC' if options[:order] == 'desc'
if options[:sort] == "last_login"
case options[:sort]
when "last_login"
users_scope.select("users.*").order(Arel.sql("last_login#{order}"))
elsif options[:sort] == "username"
when "username"
users_scope.select("users.*").order_by_sortable_name(direction: options[:order] == 'desc' ? :descending : :ascending)
elsif options[:sort] == "email"
when "email"
users_scope = users_scope.select("users.*, (SELECT path FROM #{CommunicationChannel.quoted_table_name}
WHERE communication_channels.user_id = users.id AND
communication_channels.path_type = 'email' AND
@ -89,7 +91,7 @@ module UserSearch
LIMIT 1)
AS email")
users_scope.order(Arel.sql("email#{order}"))
elsif options[:sort] == "sis_id"
when "sis_id"
users_scope = users_scope.select(User.send(:sanitize_sql, [
"users.*, (SELECT sis_user_id FROM #{Pseudonym.quoted_table_name}
WHERE pseudonyms.user_id = users.id AND

View File

@ -218,7 +218,8 @@ module VeriCite
consumer = @account_id
consumer_secret = @shared_secret
if command == :create_assignment
case command
when :create_assignment
context_id = course.id
assignment_id = assignment.id
assignment_data = VeriCiteClient::AssignmentData.new()
@ -243,7 +244,7 @@ module VeriCite
end
# this is a flag to signal success
response[:assignment_id] = assignment.id
elsif command == :submit_paper
when :submit_paper
context_id = course.id
assignment_id = assignment.id
user_id = user.id
@ -279,7 +280,7 @@ module VeriCite
end
# this is a flag to signal success
response[:returned_object_id] = external_content_data.external_content_id
elsif command == :get_scores
when :get_scores
context_id = course.id
assignment_id = assignment.id
user_id = user.id
@ -328,7 +329,7 @@ module VeriCite
end
end
end
elsif command == :generate_report
when :generate_report
context_id = course.id
assignment_id_filter = assignment.id
user_id = user.id

View File

@ -762,9 +762,10 @@ describe TabsController, type: :request do
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs", { :controller => 'tabs', :action => 'index',
:course_id => @course.to_param, :format => 'json' })
json.each do |t|
if t['visibility'] == 'public'
case t['visibility']
when 'public'
expect(public_visibility).to include(t['id'])
elsif t['visibility'] == 'admins'
when 'admins'
expect(admins_visibility).to include(t['id'])
else
expect(true).to be_falsey

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