RuboCop: Lint

[skip-stages=Flakey]

auto corrections applied:
 * Lint/AmbiguousOperator
 * Lint/AmbiguousOperatorPrecedence
 * Lint/AmbiguousRegexpLiteral
 * Lint/DeprecatedClassMethods
 * Lint/DeprecatedOpenSSLConstant
 * Lint/NonDeterministicRequireOrder
 * Lint/ParenthesesAsGroupedExpression
 * Lint/RedundantRequireStatement
 * Lint/RedundantSafeNavigation
 * Lint/RedundantSplatExpansion
 * Lint/RedundantStringCoercion
 * Lint/RedundantWithIndex
 * Lint/SendWithMixinArgument
 * Lint/SymbolConversion

Change-Id: I222ec19978033544513bb99755994d109435abad
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/274551
Tested-by: Service Cloud Jenkins <svc.cloudjenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
QA-Review: Cody Cutrer <cody@instructure.com>
Product-Review: Cody Cutrer <cody@instructure.com>
This commit is contained in:
Cody Cutrer 2021-09-27 09:58:39 -06:00
parent 117d484c1c
commit dbd8c46655
363 changed files with 1277 additions and 1263 deletions

View File

@ -31,8 +31,38 @@ Layout:
Layout/LineLength:
Enabled: false # TODO. Maybe.
Lint/AmbiguousOperator:
Severity: error
Lint/AmbiguousOperatorPrecedence:
Severity: error
Lint/AmbiguousRegexpLiteral:
Severity: error
Lint/Debugger:
Severity: error
Lint/DeprecatedClassMethods:
Severity: error
Lint/DeprecatedOpenSSLConstant:
Severity: error
Lint/NonDeterministicRequireOrder:
Severity: error
Lint/ParenthesesAsGroupedExpression:
Severity: error
Lint/RedundantRequireStatement:
Severity: error
Lint/RedundantSafeNavigation:
Severity: error
Lint/RedundantSplatExpansion:
Severity: error
Lint/RedundantStringCoercion:
Severity: error
Lint/RedundantWithIndex:
Severity: error
Lint/SendWithMixinArgument:
Severity: error
Lint/SymbolConversion:
Severity: error
Lint/UnifiedInteger:
Severity: error
Metrics:
Enabled: false # SnR is just too low to have this enabled
@ -102,6 +132,14 @@ Style/SpecialGlobalVars:
Lint/AmbiguousBlockAssociation: # TODO
Exclude:
- spec/**/*
Lint/UnusedBlockArgument: # TODO maually fix these by removing the argument if possible
Severity: warning
AutoCorrect: false
Lint/UnusedMethodArgument: # TODO maually fix these by removing the argument if possible
Severity: warning
AutoCorrect: false
Lint/UselessAssignment: # TODO
Severity: warning
Naming/VariableNumber: # TODO
Enabled: false

View File

@ -841,7 +841,7 @@ class AccountsController < ApplicationController
@account.errors.add(quota_type, t(:quota_integer_required, 'An integer value is required'))
else
@account.errors.add(quota_type, t(:quota_must_be_positive, 'Value must be positive')) if quota_value.to_i < 0
@account.errors.add(quota_type, t(:quota_too_large, 'Value too large')) if quota_value.to_i >= 2**62 / 1.megabytes
@account.errors.add(quota_type, t(:quota_too_large, 'Value too large')) if quota_value.to_i >= (2**62) / 1.megabytes
end
end
else

View File

@ -707,7 +707,7 @@ class ApplicationController < ActionController::Base
end
def tab_enabled?(id, opts = {})
return true unless @context&.respond_to?(:tabs_available)
return true unless @context.respond_to?(:tabs_available)
valid = Rails.cache.fetch(['tab_enabled4', id, @context, @current_user, @domain_root_account, session[:enrollment_uuid]].cache_key) do
@context.tabs_available(@current_user,
@ -1504,7 +1504,7 @@ class ApplicationController < ActionController::Base
def log_gets
if @page_view && !request.xhr? && request.get? && (((response.media_type || "").to_s.match(/html/)) ||
(Setting.get('create_get_api_page_views', 'true') == 'true') && api_request?)
((Setting.get('create_get_api_page_views', 'true') == 'true') && api_request?))
@page_view.render_time ||= (Time.now.utc - @page_before_render) rescue nil
@page_view_update = true
end
@ -2845,7 +2845,7 @@ class ApplicationController < ActionController::Base
}.freeze
def show_student_view_button?
return false unless @context&.is_a?(Course) && can_do(@context, @current_user, :use_student_view)
return false unless @context.is_a?(Course) && can_do(@context, @current_user, :use_student_view)
controller_action = "#{params[:controller]}##{params[:action]}"
STUDENT_VIEW_PAGES.key?(controller_action) && (STUDENT_VIEW_PAGES[controller_action].nil? || !@context.tab_hidden?(STUDENT_VIEW_PAGES[controller_action]))

View File

@ -1697,7 +1697,7 @@ class CoursesController < ApplicationController
row = []
row << opc.user.last_name
row << opc.user.first_name
row << '="' + opc.code + '"'
row << ('="' + opc.code + '"')
row << opc.expires_at
csv << row
end
@ -1772,7 +1772,7 @@ class CoursesController < ApplicationController
enrollment = nil
return false
end
elsif !@current_user && enrollment.user.registered? || !enrollment.user.email_channel
elsif (!@current_user && enrollment.user.registered?) || !enrollment.user.email_channel
session[:return_to] = course_url(@context.id)
flash[:notice] = t('notices.login_to_accept', "You'll need to log in before you can accept the enrollment.")
return redirect_to login_url(:force_login => 1) if @current_user
@ -2869,8 +2869,8 @@ class CoursesController < ApplicationController
end
if params_for_update.key?(:template)
template = value_to_boolean(params_for_update.delete(:template))
if template && @course.grants_right?(@current_user, session, :add_course_template) ||
!template && @course.grants_right?(@current_user, session, :delete_course_template)
if (template && @course.grants_right?(@current_user, session, :add_course_template)) ||
(!template && @course.grants_right?(@current_user, session, :delete_course_template))
@course.template = template
end
end

View File

@ -1533,7 +1533,7 @@ class DiscussionTopicsController < ApplicationController
def handle_assignment_edit_params(hash)
hash[:title] = params[:title] if params[:title]
if params.slice(*[:due_at, :points_possible, :assignment_group_id]).present?
if params.slice(:due_at, :points_possible, :assignment_group_id).present?
if hash[:assignment].nil? && @context.respond_to?(:assignments) && @context.assignments.temp_record.grants_right?(@current_user, session, :create)
hash[:assignment] ||= {}
end

View File

@ -634,7 +634,7 @@ class FilesController < ApplicationController
[json[:attachment],
doc_preview_json(attachment, @current_user),
attachment_json(attachment, @current_user, {}, json_include)].reduce &:merge!
attachment_json(attachment, @current_user, {}, json_include)].reduce(&:merge!)
log_asset_access(attachment, "files", "files")
end
@ -843,7 +843,7 @@ class FilesController < ApplicationController
@context = @attachment.context
@attachment.workflow_state = nil
@attachment.uploaded_data = params[:file] || params[:attachment] && params[:attachment][:uploaded_data]
@attachment.uploaded_data = params[:file] || (params[:attachment] && params[:attachment][:uploaded_data])
if @attachment.save
# for consistency with the s3 upload client flow, we redirect to the success url here to finish up
includes = Array(params[:success_include])

View File

@ -96,7 +96,7 @@ module LiveAssessments
assessment.save!
if @outcome
criterion = @outcome.rubric_criterion
mastery_score = criterion && criterion[:mastery_points] / criterion[:points_possible]
mastery_score = criterion && (criterion[:mastery_points] / criterion[:points_possible])
@outcome.align(assessment, @context, mastery_type: "none", mastery_score: mastery_score)
end
@assessments << assessment

View File

@ -34,8 +34,8 @@ class Login::OtpController < ApplicationController
def new
# if we waiting on OTP for login, but we're not yet configured, start configuring
# OR if we're not waiting on OTP, we're configuring
if session[:pending_otp] && !secret_key ||
!session[:pending_otp] && !configuring?
if (session[:pending_otp] && !secret_key) ||
(!session[:pending_otp] && !configuring?)
session[:pending_otp_secret_key] = ROTP::Base32.random
@first_reconfiguration = true
end
@ -93,7 +93,7 @@ class Login::OtpController < ApplicationController
drift = 300 if session[:pending_otp_communication_channel_id] ||
(!session[:pending_otp_secret_key] && @current_user.otp_communication_channel_id)
if !force_fail && ROTP::TOTP.new(secret_key).verify(verification_code, drift_behind: drift, drift_ahead: drift) ||
if (!force_fail && ROTP::TOTP.new(secret_key).verify(verification_code, drift_behind: drift, drift_ahead: drift)) ||
@current_user.authenticate_one_time_password(verification_code)
if configuring?
@current_user.one_time_passwords.scope.delete_all

View File

@ -173,7 +173,7 @@ module Lti
def update
sub = params.require(:subscription)
SubscriptionsValidator.validate_subscription_context!(sub) if sub[:ContextType]
updates = add_updater({ 'Id': params[:id] }.merge(sub.to_unsafe_h))
updates = add_updater({ Id: params[:id] }.merge(sub.to_unsafe_h))
response = Services::LiveEventsSubscriptionService.update(jwt_body, updates)
forward_service_response(response)
end

View File

@ -131,7 +131,7 @@ module Lti
def public_course?
# Is the context published and public?
context&.is_a?(Course) && context&.available? && context&.is_public?
context.is_a?(Course) && context&.available? && context&.is_public?
end
def verifier

View File

@ -26,7 +26,7 @@ module Lti::Ims::Providers
attr_reader :context, :controller, :tool
def self.unwrap(wrapped)
wrapped&.respond_to?(:unwrap) ? wrapped.unwrap : wrapped
wrapped.respond_to?(:unwrap) ? wrapped.unwrap : wrapped
end
def initialize(context, controller, tool)

View File

@ -347,7 +347,7 @@ class ProfileController < ApplicationController
user_params.delete(:short_name)
user_params.delete(:sortable_name)
end
if !@domain_root_account.can_change_pronouns? || user_params[:pronouns].present? && @domain_root_account.pronouns.exclude?(user_params[:pronouns].strip)
if !@domain_root_account.can_change_pronouns? || (user_params[:pronouns].present? && @domain_root_account.pronouns.exclude?(user_params[:pronouns].strip))
user_params.delete(:pronouns)
end
if @user.update(user_params)

View File

@ -656,8 +656,8 @@ class Quizzes::QuizzesController < ApplicationController
@submissions_from_users[student.id].id
end
submitted_students_json = @submitted_students.map &:id
unsubmitted_students_json = @unsubmitted_students.map &:id
submitted_students_json = @submitted_students.map(&:id)
unsubmitted_students_json = @unsubmitted_students.map(&:id)
else
submitted_students_json = @submitted_students.map { |u| user_json(u, @current_user, session) }
unsubmitted_students_json = @unsubmitted_students.map { |u| user_json(u, @current_user, session) }

View File

@ -146,7 +146,7 @@ class RubricAssociationsController < ApplicationController
def can_manage_rubrics_or_association_object?(association, association_object)
return true if association ||
@context.grants_right?(@current_user, session, :manage_rubrics) ||
association_object && association_object.grants_right?(@current_user, session, :update)
(association_object && association_object.grants_right?(@current_user, session, :update))
render_unauthorized_action
false

View File

@ -222,8 +222,8 @@ class RubricsController < ApplicationController
private
def can_manage_rubrics_or_association_object?(object)
return true if object && (can_update?(object) || can_read?(object) && can_manage_rubrics_context?) ||
!object && can_manage_rubrics_context?
return true if (object && (can_update?(object) || (can_read?(object) && can_manage_rubrics_context?))) ||
(!object && can_manage_rubrics_context?)
render_unauthorized_action
false

View File

@ -54,7 +54,7 @@ class SubAccountsController < ApplicationController
permissions: [:manage_account_settings, :manage_courses, :manage_courses_admin]
)
@query = params[:account] && params[:account][:name] || params[:term]
@query = (params[:account] && params[:account][:name]) || params[:term]
if @query
@accounts = []
if @context && @context.is_a?(Account)

View File

@ -1224,7 +1224,7 @@ class SubmissionsApiController < ApplicationController
def bulk_load_attachments_and_previews(submissions)
Submission.bulk_load_versioned_attachments(submissions)
attachments = submissions.flat_map &:versioned_attachments
attachments = submissions.flat_map(&:versioned_attachments)
ActiveRecord::Associations::Preloader.new.preload(attachments,
[:canvadoc, :crocodoc_document])
Version.preload_version_number(submissions)

View File

@ -322,12 +322,12 @@ class UsersController < ApplicationController
Canvas::Errors.capture_exception(:oauth, e, :warn)
flash[:error] = e.to_s
end
return redirect_to (@current_user ? user_profile_url(@current_user) : root_url)
return redirect_to(@current_user ? user_profile_url(@current_user) : root_url)
end
if !oauth_request || (request.host_with_port == oauth_request.original_host_with_port && oauth_request.user != @current_user)
flash[:error] = t('oauth_fail', "OAuth Request failed. Couldn't find valid request")
redirect_to (@current_user ? user_profile_url(@current_user) : root_url)
redirect_to(@current_user ? user_profile_url(@current_user) : root_url)
elsif request.host_with_port != oauth_request.original_host_with_port
url = url_for request.parameters.merge(:host => oauth_request.original_host_with_port, :only_path => false)
redirect_to url
@ -2883,7 +2883,7 @@ class UsersController < ApplicationController
force_validations = value_to_boolean(params[:force_validations])
manage_user_logins = @context.grants_right?(@current_user, session, :manage_user_logins)
self_enrollment = params[:self_enrollment].present?
allow_non_email_pseudonyms = !force_validations && manage_user_logins || self_enrollment && params[:pseudonym_type] == 'username'
allow_non_email_pseudonyms = (!force_validations && manage_user_logins) || (self_enrollment && params[:pseudonym_type] == 'username')
require_password = self_enrollment && allow_non_email_pseudonyms
allow_password = require_password || manage_user_logins || use_pairing_code
@ -3016,7 +3016,7 @@ class UsersController < ApplicationController
@cc.confirmation_redirect = cc_confirmation_redirect
end
if @recaptcha_errors.nil? && @user.valid? && @pseudonym.valid? && @invalid_observee_creds.nil? & @invalid_observee_code.nil?
if @recaptcha_errors.nil? && @user.valid? && @pseudonym.valid? && (@invalid_observee_creds.nil? & @invalid_observee_code.nil?)
# saving the user takes care of the @pseudonym and @cc, so we can't call
# save_without_session_maintenance directly. we don't want to auto-log-in
# unless the user is registered/pre_registered (if the latter, he still

View File

@ -124,7 +124,7 @@ module Types
if !apply_overrides && course.grants_any_right?(current_user, *RoleOverride::GRANULAR_MANAGE_ASSIGNMENT_PERMISSIONS)
assignment.send(field_name)
else
OverrideAssignmentLoader.for(current_user).load(assignment).then &field_name
OverrideAssignmentLoader.for(current_user).load(assignment).then(&field_name)
end
end
end

View File

@ -293,7 +293,7 @@ module ApplicationHelper
def css_variant(opts = {})
variant = use_responsive_layout? ? 'responsive_layout' : 'new_styles'
use_high_contrast = @current_user && @current_user.prefers_high_contrast? || opts[:force_high_contrast]
use_high_contrast = (@current_user && @current_user.prefers_high_contrast?) || opts[:force_high_contrast]
variant + (use_high_contrast ? '_high_contrast' : '_normal_contrast') + (I18n.rtl? ? '_rtl' : '')
end

View File

@ -126,7 +126,7 @@ module AttachmentHelper
cancel_cache_buster
# set cache to expire whenever the s3 url does (or one day if local or inline proxy), max-age take seconds, and Expires takes a date
ttl = direct ? 1.day : attachment.url_ttl
response.headers["Cache-Control"] = "private, max-age=#{ttl.seconds.to_s}"
response.headers["Cache-Control"] = "private, max-age=#{ttl.seconds}"
response.headers["Expires"] = ttl.from_now.httpdate
end
end

View File

@ -28,7 +28,7 @@ module AvatarHelper
if session["reported_#{user_id}"] && !is_admin && !(user && user.avatar_state == :approved)
["/images/messages/avatar-50.png", '']
else
avatar_settings = @domain_root_account && @domain_root_account.settings[:avatars] || 'enabled'
avatar_settings = (@domain_root_account && @domain_root_account.settings[:avatars]) || 'enabled'
user_id = Shard.global_id_for(user_id)
user_shard = Shard.shard_for(user_id)
image_url, alt_tag = user_shard.activate do
@ -103,7 +103,7 @@ module AvatarHelper
default_avatar = use_fallback ? User.avatar_fallback_url(User.default_avatar_fallback, request) : nil
url = if avatars_enabled_for_user?(user, root_account: root_account)
user.avatar_url(nil,
(root_account && root_account.settings[:avatars] || 'enabled'),
((root_account && root_account.settings[:avatars]) || 'enabled'),
default_avatar,
request,
use_fallback)

View File

@ -23,16 +23,16 @@ module ContextModulesHelper
include CyoeHelper
TRANSLATED_COMMENT_TYPE = {
'Announcement': I18n.t('Announcement'),
'Assignment': I18n.t('Assignment'),
'Attachment': I18n.t('Attachment'),
'ContextExternalTool': I18n.t('External Tool'),
'ContextModuleSubHeader': I18n.t('Context Module Sub Header'),
'DiscussionTopic': I18n.t('Discussion Topic'),
'ExternalUrl': I18n.t('External Url'),
'Quiz': I18n.t('Quiz'),
Announcement: I18n.t('Announcement'),
Assignment: I18n.t('Assignment'),
Attachment: I18n.t('Attachment'),
ContextExternalTool: I18n.t('External Tool'),
ContextModuleSubHeader: I18n.t('Context Module Sub Header'),
DiscussionTopic: I18n.t('Discussion Topic'),
ExternalUrl: I18n.t('External Url'),
Quiz: I18n.t('Quiz'),
'Quizzes::Quiz': I18n.t('Quiz'),
'WikiPage': I18n.t('Page')
WikiPage: I18n.t('Page')
}.freeze
def cache_if_module(context_module, editable, is_student, can_view_unpublished, user, context, &block)

View File

@ -154,7 +154,7 @@ module GradebooksHelper
end
def pass_fail_icon(score, grade)
if score && score > 0 || grade == 'complete'
if (score && score > 0) || grade == 'complete'
icon_attrs = pass_icon_attributes
else
icon_attrs = fail_icon_attributes

View File

@ -462,9 +462,9 @@ module QuizzesHelper
end
if answer_list.empty?
answers.delete_if { |k, v| !k.match /^question_#{hash_get(question, :id)}/ }
answers.each { |k, v| res.sub! /\{\{#{k}\}\}/, h(v) }
res.gsub! /\{\{question_[^}]+\}\}/, ""
answers.delete_if { |k, v| !k.match(/^question_#{hash_get(question, :id)}/) }
answers.each { |k, v| res.sub!(/\{\{#{k}\}\}/, h(v)) }
res.gsub!(/\{\{question_[^}]+\}\}/, "")
end
# all of our manipulation lost this flag - reset it

View File

@ -142,7 +142,7 @@ module SearchHelper
end
def search_contexts_and_users(options = {})
types = (options[:types] || [] + [options[:type]]).compact
types = (options[:types] || ([] + [options[:type]])).compact
types |= [:course, :section, :group] if types.delete('context')
types = if types.present?
{ user: types.delete('user').present?, context: types.present? && types.map(&:to_sym) }

View File

@ -258,7 +258,7 @@ class AccountNotification < ActiveRecord::Base
# we just need a stable reference point, doesn't matter what it is, so
# let's use unix epoch
start_time = Time.at(0).utc
months_since_start_time = (current_time.year - start_time.year) * 12 + (current_time.month - start_time.month)
months_since_start_time = ((current_time.year - start_time.year) * 12) + (current_time.month - start_time.month)
periods_since_start_time = months_since_start_time / months_in_period
months_into_current_period = months_since_start_time % months_in_period
mod_value = (Random.new(periods_since_start_time).rand(months_in_period) + months_into_current_period) % months_in_period

View File

@ -36,7 +36,7 @@ class AppointmentGroup < ActiveRecord::Base
end
def contexts
appointment_group_contexts.map &:context
appointment_group_contexts.map(&:context)
end
def active_contexts
@ -45,7 +45,7 @@ class AppointmentGroup < ActiveRecord::Base
def sub_contexts
# I wonder how rails is adding multiples of the same sub_contexts
appointment_group_sub_contexts.map &:sub_context
appointment_group_sub_contexts.map(&:sub_context)
end
validates_presence_of :workflow_state
@ -184,7 +184,7 @@ class AppointmentGroup < ActiveRecord::Base
end
def sub_context_codes
appointment_group_sub_contexts.map &:sub_context_code
appointment_group_sub_contexts.map(&:sub_context_code)
end
# complements :reserve permission

View File

@ -24,7 +24,7 @@ class AppointmentGroupSubContext < ActiveRecord::Base
validates_each :sub_context do |record, attr, value|
if record.participant_type == 'User'
record.errors.add(attr, t('errors.invalid_course_section', 'Invalid course section')) unless value.blank? || value.is_a?(CourseSection) && record.appointment_group.contexts.any? { |c| c == value.course }
record.errors.add(attr, t('errors.invalid_course_section', 'Invalid course section')) unless value.blank? || (value.is_a?(CourseSection) && record.appointment_group.contexts.any? { |c| c == value.course })
else
record.errors.add(attr, t('errors.missing_group_category', 'Group appointments must have a group category')) unless value.present? && value.is_a?(GroupCategory)
record.errors.add(attr, t('errors.invalid_group_category', 'Invalid group category')) unless value && record.appointment_group.contexts.any? { |c| c == value.context }

View File

@ -2160,7 +2160,7 @@ class Assignment < ActiveRecord::Base
raise "Student Required" unless original_student
group, students = group_students(original_student)
opts[:author] ||= opts[:commenter] || opts[:user_id].present? && User.find_by(id: opts[:user_id])
opts[:author] ||= opts[:commenter] || (opts[:user_id].present? && User.find_by(id: opts[:user_id]))
res = {
comments: [],
submissions: []

View File

@ -370,7 +370,7 @@ class AssignmentOverride < ActiveRecord::Base
self.assignment.created_at < 3.hours.ago &&
(saved_change_to_workflow_state? ||
saved_change_to_due_at_overridden? ||
due_at_overridden && !Assignment.due_dates_equal?(due_at, due_at_before_last_save))
(due_at_overridden && !Assignment.due_dates_equal?(due_at, due_at_before_last_save)))
end
def set_title_if_needed

View File

@ -903,9 +903,9 @@ class Attachment < ActiveRecord::Base
end
def can_be_proxied?
mime_class == 'html' && size < Setting.get('max_inline_html_proxy_size', 128 * 1024).to_i ||
mime_class == 'flash' && size < Setting.get('max_swf_proxy_size', 1024 * 1024).to_i ||
content_type == 'text/css' && size < Setting.get('max_css_proxy_size', 64 * 1024).to_i
(mime_class == 'html' && size < Setting.get('max_inline_html_proxy_size', 128 * 1024).to_i) ||
(mime_class == 'flash' && size < Setting.get('max_swf_proxy_size', 1024 * 1024).to_i) ||
(content_type == 'text/css' && size < Setting.get('max_css_proxy_size', 64 * 1024).to_i)
end
def local_storage_path
@ -1028,7 +1028,7 @@ class Attachment < ActiveRecord::Base
block ||= lambda { |str, len| str[0...len] }
ext_index = filename.rindex('.')
if ext_index
ext = block.call(filename[ext_index..-1], len / 2 + 1)
ext = block.call(filename[ext_index..-1], (len / 2) + 1)
base = block.call(filename[0...ext_index], len - ext.length)
base + ext
else

View File

@ -29,7 +29,7 @@ class Attachments::LocalStorage
end
def exists?
File.exists?(attachment.full_filename)
File.exist?(attachment.full_filename)
end
def change_namespace(old_full_filename)

View File

@ -86,7 +86,7 @@ class Attachments::S3Storage
def shared_secret(datetime)
config = bucket.client.config
sha256 = OpenSSL::Digest::SHA256.new
sha256 = OpenSSL::Digest.new('SHA256')
date_key = OpenSSL::HMAC.digest(sha256, "AWS4#{config.secret_access_key}", datetime[0, 8])
date_region_key = OpenSSL::HMAC.digest(sha256, date_key, config.region)
date_region_service_key = OpenSSL::HMAC.digest(sha256, date_region_key, "s3")

View File

@ -130,7 +130,7 @@ class CalendarEvent < ActiveRecord::Base
end
def effective_context
effective_context_code && ActiveRecord::Base.find_all_by_asset_string(effective_context_code).first || context
(effective_context_code && ActiveRecord::Base.find_all_by_asset_string(effective_context_code).first) || context
end
scope :active, -> { where("calendar_events.workflow_state<>'deleted'") }
@ -661,7 +661,7 @@ class CalendarEvent < ActiveRecord::Base
given { |user, session|
appointment_group? && (
grants_right?(user, session, :manage) ||
context.grants_right?(user, :reserve) && context.participant_for(user).present?
(context.grants_right?(user, :reserve) && context.participant_for(user).present?)
)
}
can :reserve

View File

@ -54,7 +54,7 @@ class Canvadoc < ActiveRecord::Base
def submissions
self.canvadocs_submissions
.preload(submission: :assignment)
.map &:submission
.map(&:submission)
end
def available?

View File

@ -615,7 +615,7 @@ class ContentMigration < ActiveRecord::Base
self.update_master_migration('failed') if self.for_master_course_import?
raise e
ensure
File.delete(all_files_path) if all_files_path && File.exists?(all_files_path)
File.delete(all_files_path) if all_files_path && File.exist?(all_files_path)
clear_migration_data
end
end

View File

@ -96,7 +96,7 @@ module Context
context_codes = sharded_course_ids.map { |id| "course_#{id}" }
if Shard.current == self.shard
context = self
while context && context.respond_to?(:account) || context.respond_to?(:parent_account)
while (context && context.respond_to?(:account)) || context.respond_to?(:parent_account)
context = context.respond_to?(:account) ? context.account : context.parent_account
context_codes << context.asset_string if context
end

View File

@ -241,7 +241,7 @@ class ContextModule < ActiveRecord::Base
# kept in the same module.
def duplicate_content_tag(original_content_tag)
new_tag = duplicate_content_tag_base_model(original_content_tag)
if original_content_tag.content&.respond_to?(:duplicate)
if original_content_tag.content.respond_to?(:duplicate)
new_tag.content = original_content_tag.content.duplicate
# If we have multiple assignments (e.g.) make sure they each get unused titles.
# A title isn't marked used if the assignment hasn't been saved yet.
@ -634,7 +634,7 @@ class ContextModule < ActiveRecord::Base
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] || ((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"
item = opts[:wiki_page] || self.context.wiki_pages.where(id: params[:id]).first

View File

@ -91,7 +91,7 @@ class ConversationBatch < ActiveRecord::Base
# headway. every minute we will advance half of the remainder of
# job_start_factor.
minutes = (Time.zone.now - created_at).to_i / 60.0
job_start_factor * (1 - (1 / 2**minutes))
job_start_factor * (1 - (1 / (2**minutes)))
else
# the rest of the progress bar is nice and linear
job_start_factor + ((1 - job_start_factor) * conversation_message_ids.size / recipient_ids.size)

View File

@ -302,7 +302,7 @@ class ConversationMessage < ActiveRecord::Base
end
def forwarded_messages
@forwarded_messages ||= forwarded_message_ids && self.class.unscoped { self.class.where(id: forwarded_message_ids.split(',')).order('created_at DESC').to_a } || []
@forwarded_messages ||= (forwarded_message_ids && self.class.unscoped { self.class.where(id: forwarded_message_ids.split(',')).order('created_at DESC').to_a }) || []
end
def all_forwarded_messages

View File

@ -1162,7 +1162,7 @@ class Course < ActiveRecord::Base
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.workflow_state_changed? || (sis_batch && self.saved_change_to_workflow_state?)
if self.completed?
enrollment_info = Enrollment.where(:course_id => self, :workflow_state => ['active', 'invited']).select(:id, :workflow_state).to_a
if enrollment_info.any?
@ -1625,7 +1625,7 @@ class Course < ActiveRecord::Base
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")) && (self.available? || self.completed? || (self.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? } }

View File

@ -992,8 +992,8 @@ class DiscussionTopic < ActiveRecord::Base
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)
(!self.published? && self.saved_change_to_attribute?(:workflow_state)) ||
(self.is_announcement && self.not_available_yet? && self.saved_change_to_attribute?(:delayed_post_at))
end
def clear_non_applicable_stream_items
@ -1341,7 +1341,7 @@ class DiscussionTopic < ActiveRecord::Base
end
def visible_to_admins_only?
self.context.respond_to?(:available?) && !self.context.available? ||
(self.context.respond_to?(:available?) && !self.context.available?) ||
unpublished? || not_available_yet? || not_available_anymore?
end

View File

@ -1414,10 +1414,10 @@ class Enrollment < ActiveRecord::Base
# find it, fall back to the section or course creation date.
enrollment_dates.map(&:first).compact.min ||
start_at ||
course_section && course_section.start_at ||
(course_section && course_section.start_at) ||
course.start_at ||
course.enrollment_term && course.enrollment_term.start_at ||
course_section && course_section.created_at ||
(course.enrollment_term && course.enrollment_term.start_at) ||
(course_section && course_section.created_at) ||
course.created_at
end
@ -1427,9 +1427,9 @@ class Enrollment < ActiveRecord::Base
# looking at the enrollment, section, course, then term.
enrollment_dates.map(&:last).compact.max ||
end_at ||
course_section && course_section.end_at ||
(course_section && course_section.end_at) ||
course.conclude_at ||
course.enrollment_term && course.enrollment_term.end_at
(course.enrollment_term && course.enrollment_term.end_at)
end
def self.cross_shard_invitations?
@ -1540,10 +1540,10 @@ class Enrollment < ActiveRecord::Base
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.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))
end
def remove_user_as_final_grader?

View File

@ -52,7 +52,7 @@ 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
!self.state_is_current? || (self.state_valid_until && self.state_valid_until < Time.now)
end
def ensure_current_state

View File

@ -57,7 +57,7 @@ class EportfolioEntry < ActiveRecord::Base
protected :update_portfolio
def content_sections
(self.content.is_a?(String) && Array(self.content) || self.content || []).map do |section|
((self.content.is_a?(String) && Array(self.content)) || self.content || []).map do |section|
if section.is_a?(Hash)
section.with_indifferent_access
else

View File

@ -127,7 +127,7 @@ class FeatureFlag < ActiveRecord::Base
private
def valid_state
unless [Feature::STATE_OFF, Feature::STATE_ON].include?(state) || context.is_a?(Account) && [Feature::STATE_DEFAULT_OFF, Feature::STATE_DEFAULT_ON].include?(state)
unless [Feature::STATE_OFF, Feature::STATE_ON].include?(state) || (context.is_a?(Account) && [Feature::STATE_DEFAULT_OFF, Feature::STATE_DEFAULT_ON].include?(state))
errors.add(:state, "is not valid in context")
end
end

View File

@ -113,9 +113,9 @@ class GradingStandard < ActiveRecord::Base
# otherwise, we step down just 1/10th of a point, which is the
# granularity we support right now
elsif idx && (ordered_scheme[idx].last - ordered_scheme[idx - 1].last).abs >= 0.01.to_d
ordered_scheme[idx - 1].last * 100.0.to_d - 1.0.to_d
(ordered_scheme[idx - 1].last * 100.0.to_d) - 1.0.to_d
elsif idx
ordered_scheme[idx - 1].last * 100.0.to_d - 0.1.to_d
(ordered_scheme[idx - 1].last * 100.0.to_d) - 0.1.to_d
else
nil
end

View File

@ -158,7 +158,7 @@ module Importers
end
if asset
options = alignment.slice(*[:mastery_type, :mastery_score])
options = alignment.slice(:mastery_type, :mastery_score)
item.align(asset, context, options)
end
end

View File

@ -64,7 +64,7 @@ module Importers
return unless node[attr].present?
if attr == 'value'
return unless node[attr] && node[attr] =~ %r{IMS(?:-|_)CC(?:-|_)FILEBASE} || node[attr] =~ %r{CANVAS_COURSE_REFERENCE}
return unless (node[attr] && node[attr] =~ %r{IMS(?:-|_)CC(?:-|_)FILEBASE}) || node[attr] =~ %r{CANVAS_COURSE_REFERENCE}
end
url = node[attr].dup
@ -143,14 +143,14 @@ module Importers
elsif url =~ %r{\$IMS(?:-|_)CC(?:-|_)FILEBASE\$/(.*)}
rel_path = URI.unescape($1)
if attr == 'href' && node['class'] && node['class'] =~ /instructure_inline_media_comment/ ||
attr == 'src' && node.name == 'iframe' && node['data-media-id']
if (attr == 'href' && node['class'] && node['class'] =~ /instructure_inline_media_comment/) ||
(attr == 'src' && node.name == 'iframe' && node['data-media-id'])
unresolved(:media_object, :rel_path => rel_path)
else
unresolved(:file, :rel_path => rel_path)
end
elsif attr == 'href' && node['class'] && node['class'] =~ /instructure_inline_media_comment/ ||
attr == 'src' && node.name == 'iframe' && node['data-media-id']
elsif (attr == 'href' && node['class'] && node['class'] =~ /instructure_inline_media_comment/) ||
(attr == 'src' && node.name == 'iframe' && node['data-media-id'])
# Course copy media reference, leave it alone
resolved
elsif attr == 'src' && (info_match = url.match(/\Adata:(?<mime_type>[-\w]+\/[-\w\+\.]+)?;base64,(?<image>.*)/m))

View File

@ -160,7 +160,7 @@ module IncomingMail
end
def parse_tag(tag)
match = tag.match /^(\h+)-([0-9~]+)(?:-([0-9]+))?$/
match = tag.match(/^(\h+)-([0-9~]+)(?:-([0-9]+))?$/)
return match[1], match[2], match[3] if match
end

View File

@ -106,7 +106,7 @@ class NotificationEndpoint < ActiveRecord::Base
# is happening.
endpoint_updated = false
if retried
raise FailedSnsInteraction, "Unable to create or reassign SNS endpoint for access_token #{access_token.global_id.to_s}"
raise FailedSnsInteraction, "Unable to create or reassign SNS endpoint for access_token #{access_token.global_id}"
end
retried = true

View File

@ -45,14 +45,14 @@ module OutcomesService
def outcome_attributes(learning_outcome)
attrs = learning_outcome.attributes.transform_keys(&:to_sym)
attrs[:'$canvas_learning_outcome_id'] = attrs.delete(:id)
attrs[:$canvas_learning_outcome_id] = attrs.delete(:id)
attrs[:rubric_criterion] = attrs.delete(:data)[:rubric_criterion]
attrs.except(:migration_id_2, :vendor_guid_2, :root_account_id, :context_type, :context_id)
end
def group_attributes(learning_outcome_group)
attrs = learning_outcome_group.attributes.transform_keys(&:to_sym)
attrs[:'$canvas_learning_outcome_group_id'] = attrs.delete(:id)
attrs[:$canvas_learning_outcome_group_id] = attrs.delete(:id)
attrs[:parent_outcome_group_id] = attrs.delete(:learning_outcome_group_id)
attrs.except(:root_learning_outcome_group_id, :root_account_id, :migration_id_2, :vendor_guid_2)
end

View File

@ -116,7 +116,7 @@ class Quizzes::QuizStatistics::ItemAnalysis::Summary
if size > 1 && variance != 0
variance_sum = items.map(&:variance).sum
size / (size - 1.0) * (1 - variance_sum / variance)
size / (size - 1.0) * (1 - (variance_sum / variance))
else
nil
end

View File

@ -31,12 +31,9 @@ class Quizzes::QuizStatisticsService
# An object ready for API serialization containing (persisted) versions of
# the *latest* Student and Item analysis for the quiz.
def generate_aggregate_statistics(all_versions, includes_sis_ids = true, options = {})
Quizzes::QuizStatisticsSerializer::Input.new(quiz, options, *[
quiz.current_statistics_for('student_analysis', {
Quizzes::QuizStatisticsSerializer::Input.new(quiz, options, quiz.current_statistics_for('student_analysis', {
includes_all_versions: all_versions,
includes_sis_ids: includes_sis_ids
}),
quiz.current_statistics_for('item_analysis')
])
}), quiz.current_statistics_for('item_analysis'))
end
end

View File

@ -33,11 +33,11 @@ module QuizzesNext
return if assignments.empty?
{
"original_course_uuid": course.uuid,
"assignments": assignments.map do |assignment|
original_course_uuid: course.uuid,
assignments: assignments.map do |assignment|
{
"original_resource_link_id": assignment.lti_resource_link_id,
"original_assignment_id": assignment.id,
original_resource_link_id: assignment.lti_resource_link_id,
original_assignment_id: assignment.id,
"$canvas_assignment_id": assignment.id # transformed to new id
}
end

View File

@ -186,7 +186,7 @@ class Role < ActiveRecord::Base
# 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)
(ENROLLMENT_TYPES.index(self.base_role_type) * 2) + (self.built_in? ? 0 : 1)
else
self.built_in? ? 0 : 1
end

View File

@ -368,7 +368,7 @@ class SisBatch < ActiveRecord::Base
end
def file_diff_percent(current_file_size, previous_zip_size)
(1 - current_file_size.to_f / previous_zip_size.to_f).abs * 100
(1 - (current_file_size.to_f / previous_zip_size.to_f)).abs * 100
end
def download_zip

View File

@ -158,7 +158,7 @@ class SisPseudonym
end
def use_loaded_collection?(shard)
user.pseudonyms.loaded? && user.shard == shard ||
(user.pseudonyms.loaded? && user.shard == shard) ||
(include_deleted ? user.all_pseudonyms_loaded? : user.all_active_pseudonyms_loaded?)
end

View File

@ -1582,7 +1582,7 @@ class Submission < ActiveRecord::Base
def score_late_or_none(late_policy, points_possible, grading_type)
raw_score = score_changed? || @regraded ? score : entered_score
deducted = late_points_deducted(raw_score, late_policy, points_possible, grading_type)
new_score = raw_score && raw_score - deducted
new_score = raw_score && (raw_score - deducted)
self.points_deducted = late? ? deducted : nil
self.score = new_score
end
@ -1945,7 +1945,7 @@ class Submission < ActiveRecord::Base
# since they're all being held on the assignment for now.
attachments ||= []
old_ids = (Array(self.attachment_ids || "").join(",")).split(",").map { |id| id.to_i }
write_attribute(:attachment_ids, attachments.select { |a| a && a.id && old_ids.include?(a.id) || (a.recently_created? && a.context == self.assignment) || a.context != self.assignment }.map { |a| a.id }.join(","))
write_attribute(:attachment_ids, attachments.select { |a| (a && a.id && old_ids.include?(a.id)) || (a.recently_created? && a.context == self.assignment) || a.context != self.assignment }.map { |a| a.id }.join(","))
end
# someday code-archaeologists will wonder how this method came to be named

View File

@ -1297,13 +1297,13 @@ class User < ActiveRecord::Base
(Account.site_admin.grants_right?(user, :reset_any_mfa)) ||
# an admin can reset another user's MFA only if they can manage *all*
# of the user's pseudonyms
self != user && self.pseudonyms.shard(self).all? do |p|
(self != user && self.pseudonyms.shard(self).all? do |p|
p.grants_right?(user, :update) ||
# the account does not have mfa enabled
p.account.mfa_settings == :disabled ||
# they are an admin user and have reset MFA permission
p.account.grants_right?(user, :reset_any_mfa)
end
end)
end
can :reset_mfa
@ -2909,7 +2909,7 @@ class User < ActiveRecord::Base
if pseudonym_hint
mfa_settings = pseudonym_hint.account.mfa_settings
return :required if mfa_settings == :required ||
mfa_settings == :required_for_admins && !pseudonym_hint.account.cached_all_account_users_for(self).empty?
(mfa_settings == :required_for_admins && !pseudonym_hint.account.cached_all_account_users_for(self).empty?)
end
return :required if pseudonym_hint&.authentication_provider&.mfa_required?
@ -2952,7 +2952,7 @@ class User < ActiveRecord::Base
# midnight sunday morning the rest of the time.
account_bucket = (shard.id.to_i + pseudonym.try(:account_id).to_i) % DelayedMessage::WEEKLY_ACCOUNT_BUCKETS
user_bucket = self.id % DelayedMessage::MINUTES_PER_WEEKLY_ACCOUNT_BUCKET
account_bucket * DelayedMessage::MINUTES_PER_WEEKLY_ACCOUNT_BUCKET + user_bucket
(account_bucket * DelayedMessage::MINUTES_PER_WEEKLY_ACCOUNT_BUCKET) + user_bucket
end
def weekly_notification_time

View File

@ -177,9 +177,9 @@ class WebConference < ActiveRecord::Base
# redirecting through here again in case the url has a short-lived token and needs to be
# regenerated)
def external_url_for(key, user, url_id = nil)
external_urls[key.to_sym] &&
(external_urls[key.to_sym] &&
respond_to?("#{key}_external_url") &&
send("#{key}_external_url", user, url_id) || []
send("#{key}_external_url", user, url_id)) || []
end
def self.external_urls
@ -355,7 +355,7 @@ class WebConference < ActiveRecord::Base
def restart
self.start_at ||= Time.now
self.end_at = self.duration && self.start_at + self.duration_in_seconds
self.end_at = self.duration && (self.start_at + self.duration_in_seconds)
self.started_at ||= self.start_at
self.ended_at = nil
self.save
@ -374,7 +374,7 @@ class WebConference < ActiveRecord::Base
def active?(force_check = false, allow_check = true)
if !force_check
return false if self.ended_at && Time.now > self.ended_at
return true if self.start_at && (self.end_at.nil? || self.end_at && Time.now > self.start_at && Time.now < self.end_at)
return true if self.start_at && (self.end_at.nil? || (self.end_at && Time.now > self.start_at && Time.now < self.end_at))
return true if self.ended_at && Time.now < self.ended_at
return @conference_active unless @conference_active.nil?
end
@ -438,7 +438,7 @@ class WebConference < ActiveRecord::Base
def craft_url(user = nil, session = nil, return_to = "http://www.instructure.com")
user ||= self.user
initiate_conference and touch or return nil
(initiate_conference and touch) or return nil
if user == self.user || self.grants_right?(user, session, :initiate)
admin_join_url(user, return_to)
else

View File

@ -183,7 +183,7 @@ class WimbaConference < WebConference
end
def admin_settings_url(user, return_to = "http://www.instructure.com")
initiate_conference and touch or return nil
(initiate_conference and touch) or return nil
add_user_to_conference(user, :admin) &&
settings_url(user)
end

View File

@ -30,7 +30,7 @@ module Quizzes
def_delegators :object, :quiz
attributes *%w[
attributes(*%w[
id
report_type
readable_type
@ -42,7 +42,7 @@ module Quizzes
progress_url
created_at
updated_at
].map(&:to_sym)
].map(&:to_sym))
has_one :quiz, embed: :ids, root: :quiz
has_one :progress, {

View File

@ -31,39 +31,30 @@ module Quizzes
root :quiz_statistics
attributes *[
# the id is really only included in JSON-API and only because the spec
# requires it, this is because the output of this serializer is a mix of
# two entities, an id doesn't make much sense, but we'll use the id of the
# StudentAnalysis when needed
:id,
attributes :id,
:url,
:html_url,
# whether any of the participants has taken the quiz more than one time
:multiple_attempts_exist,
# the time of the generation of the analysis (the earliest one)
:generated_at,
# whether the statistics were based on earlier and current quiz submissions
#
# PS: this is always true for item analysis
:includes_all_versions,
# whether statistics report includes sis ids
# always false for item analysis
:includes_sis_ids,
:points_possible,
:anonymous_survey,
:speed_grader_url,
:quiz_submissions_zip_url,
# an aggregate of question stats from both student and item analysis
:question_statistics,
# submission-related statistics (extracted from student analysis):
#
# - correct_count_average
@ -73,8 +64,7 @@ module Quizzes
# - score_high
# - score_low
# - score_stdev
:submission_statistics,
]
:submission_statistics
def_delegators :@controller,
:course_quiz_statistics_url,

View File

@ -254,7 +254,7 @@ module CanvasRails
Autoextend.hook(:"Thor::Option", PatchThorWarning, method: :prepend)
# Extend any base classes, even gem classes
Dir.glob("#{Rails.root}/lib/ext/**/*.rb").each { |file| require file }
Dir.glob("#{Rails.root}/lib/ext/**/*.rb").sort.each { |file| require file }
# tell Rails to use the native XML parser instead of REXML
ActiveSupport::XmlMini.backend = 'Nokogiri'

View File

@ -1313,7 +1313,7 @@ ActiveRecord::Relation.class_eval do
while ids.first.present?
ids.map!(&:to_i) if is_integer
ids << ids.first + batch_size if loose_mode
ids << (ids.first + batch_size) if loose_mode
yield(*ids)
last_value = ids.last
@ -1747,7 +1747,7 @@ if CANVAS_RAILS6_0
scope.scoping { super }
end
end
ActiveRecord::Base.send(:include, UnscopeCallbacks)
ActiveRecord::Base.include UnscopeCallbacks
end
module MatchWithDiscard

View File

@ -22,4 +22,4 @@ Rails.configuration.to_prepare do
BroadcastPolicy.notifier = lambda { Notifier.new }
BroadcastPolicy.notification_finder = lambda { NotificationFinder.new(Notification.all_cached) }
end
ActiveRecord::Base.send(:extend, BroadcastPolicy::ClassMethods)
ActiveRecord::Base.extend BroadcastPolicy::ClassMethods

View File

@ -19,5 +19,5 @@
require 'canvas_crummy'
ActionController::Base.send :include, CanvasCrummy::ControllerMethods
ActionView::Base.send :include, CanvasCrummy::ViewMethods
ActionController::Base.include CanvasCrummy::ControllerMethods
ActionView::Base.include CanvasCrummy::ViewMethods

View File

@ -19,4 +19,4 @@
require 'canvas_sanitize'
ActiveRecord::Base.send :include, CanvasSanitize
ActiveRecord::Base.include CanvasSanitize

View File

@ -227,4 +227,4 @@ module CanvasDelayedMessageSending
delay(sender: sender, **kwargs.merge(synchronous: !Rails.env.production?))
end
end
Object.send(:include, CanvasDelayedMessageSending)
Object.include CanvasDelayedMessageSending

View File

@ -142,7 +142,7 @@ end
if ENV['LOLCALIZE']
require 'i18n_tasks'
I18n.send :extend, I18nTasks::Lolcalize
I18n.extend I18nTasks::Lolcalize
end
module I18nUtilities
@ -173,9 +173,9 @@ module I18nUtilities
end
end
ActionView::Base.send(:include, I18nUtilities)
ActionView::Helpers::FormHelper.send(:include, I18nUtilities)
ActionView::Helpers::FormTagHelper.send(:include, I18nUtilities)
ActionView::Base.include I18nUtilities
ActionView::Helpers::FormHelper.include I18nUtilities
ActionView::Helpers::FormTagHelper.include I18nUtilities
module I18nFormHelper
# a convenience method to put the ":" after the label text (or do whatever

View File

@ -20,7 +20,7 @@
# Be sure to restart your server when you modify this file.
ActiveSupport::Inflector.inflections do |inflect|
inflect.singular /(criteri)a$/i, '\1on'
inflect.plural /(criteri)on$/i, '\1a'
inflect.singular(/(criteri)a$/i, '\1on')
inflect.plural(/(criteri)on$/i, '\1a')
inflect.acronym "GraphQL"
end

View File

@ -39,8 +39,8 @@ if Rails.env.test?
def raise(*args)
if defined?(SpecTimeLimit) && args.first == SpecTimeLimit::Error
have_ever_run_a_debugger = (
defined?(Byebug) && Byebug.respond_to?(:started?) ||
defined?(Pry) && Pry::InputLock.input_locks.any?
(defined?(Byebug) && Byebug.respond_to?(:started?)) ||
(defined?(Pry) && Pry::InputLock.input_locks.any?)
)
if have_ever_run_a_debugger
Rails.logger.warn "Ignoring timeout because we're debugging"

View File

@ -23,7 +23,7 @@ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'api_scopes'))
require 'controller_list_view'
require 'api_scope_mapping_writer'
Dir.glob("#{Rails.root}/doc/api/data_services/*.rb").each { |file| require file }
Dir.glob("#{Rails.root}/doc/api/data_services/*.rb").sort.each { |file| require file }
include Helpers::ModuleHelper
include Helpers::FilterHelper
@ -49,7 +49,7 @@ module YARD::Templates::Helpers::BaseHelper
html_file = "#{topicize topic.first}.html"
action = $2
name = controller.name.to_s
name = "#{controller.namespace.name.to_s}/#{name}" if controller.namespace.name != :root
name = "#{controller.namespace.name}/#{name}" if controller.namespace.name != :root
link_url("#{html_file}#method.#{topicize(name).sub("_controller", "")}.#{action}", args[1])
else
raise "couldn't find API link for #{args.first}"

View File

@ -100,12 +100,12 @@ def render_properties(json)
if json['description'].present?
result << render_comment(json)
end
result << "{\n" + indent(
result << ("{\n" + indent(
properties.map do |name, prop|
render_comment(prop) +
%{"#{name}": } + render_value(prop)
end.join(",\n")
) + "\n}"
) + "\n}")
end
rescue
puts "error rendering properties for model:\n#{json}"

View File

@ -29,8 +29,8 @@ RSpec.describe Audits do
def inject_auditors_settings(yaml_string)
DynamicSettings.fallback_data = {
"private": {
"canvas": {
private: {
canvas: {
"auditors.yml": yaml_string
}
}

View File

@ -82,8 +82,8 @@ module ActiveSupport::Callbacks
# end
#
def suspended_callback?(callback, kind, type = nil)
val = suspended_callbacks_defined? &&
suspended_callbacks.include?(callback, kind, type) ||
val = (suspended_callbacks_defined? &&
suspended_callbacks.include?(callback, kind, type)) ||
suspended_callback_ancestor&.suspended_callback?(callback, kind, type)
val

View File

@ -251,7 +251,7 @@ module AttachmentFu # :nodoc:
return filename if thumbnail.blank?
ext = nil
basename = filename.gsub /\.\w+$/ do |s|
basename = filename.gsub(/\.\w+$/) do |s|
ext = s; ''
end
# ImageScience doesn't create gif thumbnails, only pngs
@ -495,17 +495,17 @@ module AttachmentFu # :nodoc:
# Generates a unique filename for a Tempfile.
def random_tempfile_filename
"#{rand Time.now.to_i}#{filename && filename.last(50) || 'attachment'}"
"#{rand Time.now.to_i}#{(filename && filename.last(50)) || 'attachment'}"
end
def sanitize_filename(filename)
filename.strip.tap do |name|
# NOTE: File.basename doesn't work right with Windows paths on Unix
# get only the filename, not the whole path
name.gsub! /^.*(\\|\/)/, ''
name.gsub!(/^.*(\\|\/)/, '')
# Finally, replace all non alphanumeric, underscore or periods with underscore
name.gsub! /[^\w\.\-]/, '_'
name.gsub!(/[^\w\.\-]/, '_')
end
end

View File

@ -20,7 +20,7 @@
module AttachmentFu
class Railtie < ::Rails::Railtie
initializer "attachment_fu.canvas_plugin" do
ActiveRecord::Base.send(:extend, AttachmentFu::ActMethods)
ActiveRecord::Base.extend AttachmentFu::ActMethods
AttachmentFu::Railtie.setup_tempfile_path
end

View File

@ -60,7 +60,7 @@ class BookmarkedCollection::MergeProxy < BookmarkedCollection::CompositeProxy
indexed_bookmarks.sort!
last_item, last_leaf_bookmark = nil, nil
while indexed_bookmarks.present? && (pager.size < pager.per_page || @merge_proc && indexed_bookmarks.first.first == last_leaf_bookmark)
while indexed_bookmarks.present? && (pager.size < pager.per_page || (@merge_proc && indexed_bookmarks.first.first == last_leaf_bookmark))
# pull the index of the collection with the next lowest bookmark and
# pull off its first item
leaf_bookmark, index = indexed_bookmarks.shift

View File

@ -117,7 +117,7 @@ module BookmarkedCollection
TYPE_MAP = {
string: ->(val) { val.is_a?(String) },
integer: ->(val) { val.is_a?(Integer) },
datetime: ->(val) { val.is_a?(DateTime) || val.is_a?(Time) || val.is_a?(String) && !!(DateTime.parse(val) rescue false) }
datetime: ->(val) { val.is_a?(DateTime) || val.is_a?(Time) || (val.is_a?(String) && !!(DateTime.parse(val) rescue false)) }
}
def existing_column_definition(col_name)
@ -137,7 +137,7 @@ module BookmarkedCollection
columns.each.with_index.all? do |col, i|
type = TYPE_MAP[column_definitions[col][:type]]
nullable = column_definitions[col][:null]
type && (nullable && bookmark[i].nil? || type.(bookmark[i]))
type && ((nullable && bookmark[i].nil?) || type.(bookmark[i]))
end
end

View File

@ -36,7 +36,7 @@ module BroadcastPolicy
# reasons.
def broadcast(record)
return if record.respond_to?(:skip_broadcasts) && record.skip_broadcasts
return unless record.instance_eval &self.whenever
return unless record.instance_eval(&self.whenever)
notification = BroadcastPolicy.notification_finder.by_name(self.dispatch)
return if notification.nil?

View File

@ -33,7 +33,7 @@ module CanvasCache
raise "Redis is not enabled for this install" unless CanvasCache::Redis.enabled?
conf = CanvasCache::Redis.config
if conf == 'cache_store' || conf.is_a?(Hash) && conf['servers'] == 'cache_store'
if conf == 'cache_store' || (conf.is_a?(Hash) && conf['servers'] == 'cache_store')
return Rails.cache.redis
end

View File

@ -49,154 +49,154 @@ module CanvasColor
BRIGHTNESS_DEFAULT = 0.2
NAMED_COLORS = {
"aliceblue": "#f0f8ff",
"antiquewhite": "#faebd7",
"aqua": "#00ffff",
"aquamarine": "#7fffd4",
"azure": "#f0ffff",
"beige": "#f5f5dc",
"bisque": "#ffe4c4",
"black": "#000000",
"blanchedalmond": "#ffebcd",
"blue": "#0000ff",
"blueviolet": "#8a2be2",
"brown": "#a52a2a",
"burlywood": "#deb887",
"cadetblue": "#5f9ea0",
"chartreuse": "#7fff00",
"chocolate": "#d2691e",
"coral": "#ff7f50",
"cornflowerblue": "#6495ed",
"cornsilk": "#fff8dc",
"crimson": "#dc143c",
"cyan": "#00ffff",
"darkblue": "#00008b",
"darkcyan": "#008b8b",
"darkgoldenrod": "#b8860b",
"darkgray": "#a9a9a9",
"darkgreen": "#006400",
"darkgrey": "#a9a9a9",
"darkkhaki": "#bdb76b",
"darkmagenta": "#8b008b",
"darkolivegreen": "#556b2f",
"darkorange": "#ff8c00",
"darkorchid": "#9932cc",
"darkred": "#8b0000",
"darksalmon": "#e9967a",
"darkseagreen": "#8fbc8f",
"darkslateblue": "#483d8b",
"darkslategray": "#2f4f4f",
"darkslategrey": "#2f4f4f",
"darkturquoise": "#00ced1",
"darkviolet": "#9400d3",
"deeppink": "#ff1493",
"deepskyblue": "#00bfff",
"dimgray": "#696969",
"dimgrey": "#696969",
"dodgerblue": "#1e90ff",
"firebrick": "#b22222",
"floralwhite": "#fffaf0",
"forestgreen": "#228b22",
"fuchsia": "#ff00ff",
"gainsboro": "#dcdcdc",
"ghostwhite": "#f8f8ff",
"gold": "#ffd700",
"goldenrod": "#daa520",
"gray": "#808080",
"green": "#008000",
"greenyellow": "#adff2f",
"grey": "#808080",
"honeydew": "#f0fff0",
"hotpink": "#ff69b4",
"indianred": "#cd5c5c",
"indigo": "#4b0082",
"ivory": "#fffff0",
"khaki": "#f0e68c",
"lavender": "#e6e6fa",
"lavenderblush": "#fff0f5",
"lawngreen": "#7cfc00",
"lemonchiffon": "#fffacd",
"lightblue": "#add8e6",
"lightcoral": "#f08080",
"lightcyan": "#e0ffff",
"lightgoldenrodyellow": "#fafad2",
"lightgray": "#d3d3d3",
"lightgreen": "#90ee90",
"lightgrey": "#d3d3d3",
"lightpink": "#ffb6c1",
"lightsalmon": "#ffa07a",
"lightseagreen": "#20b2aa",
"lightskyblue": "#87cefa",
"lightslategray": "#778899",
"lightslategrey": "#778899",
"lightsteelblue": "#b0c4de",
"lightyellow": "#ffffe0",
"lime": "#00ff00",
"limegreen": "#32cd32",
"linen": "#faf0e6",
"magenta": "#ff00ff",
"maroon": "#800000",
"mediumaquamarine": "#66cdaa",
"mediumblue": "#0000cd",
"mediumorchid": "#ba55d3",
"mediumpurple": "#9370db",
"mediumseagreen": "#3cb371",
"mediumslateblue": "#7b68ee",
"mediumspringgreen": "#00fa9a",
"mediumturquoise": "#48d1cc",
"mediumvioletred": "#c71585",
"midnightblue": "#191970",
"mintcream": "#f5fffa",
"mistyrose": "#ffe4e1",
"moccasin": "#ffe4b5",
"navajowhite": "#ffdead",
"navy": "#000080",
"oldlace": "#fdf5e6",
"olive": "#808000",
"olivedrab": "#6b8e23",
"orange": "#ffa500",
"orangered": "#ff4500",
"orchid": "#da70d6",
"palegoldenrod": "#eee8aa",
"palegreen": "#98fb98",
"paleturquoise": "#afeeee",
"palevioletred": "#db7093",
"papayawhip": "#ffefd5",
"peachpuff": "#ffdab9",
"peru": "#cd853f",
"pink": "#ffc0cb",
"plum": "#dda0dd",
"powderblue": "#b0e0e6",
"purple": "#800080",
"rebeccapurple": "#663399",
"red": "#ff0000",
"rosybrown": "#bc8f8f",
"royalblue": "#4169e1",
"saddlebrown": "#8b4513",
"salmon": "#fa8072",
"sandybrown": "#f4a460",
"seagreen": "#2e8b57",
"seashell": "#fff5ee",
"sienna": "#a0522d",
"silver": "#c0c0c0",
"skyblue": "#87ceeb",
"slateblue": "#6a5acd",
"slategray": "#708090",
"slategrey": "#708090",
"snow": "#fffafa",
"springgreen": "#00ff7f",
"steelblue": "#4682b4",
"tan": "#d2b48c",
"teal": "#008080",
"thistle": "#d8bfd8",
"tomato": "#ff6347",
"turquoise": "#40e0d0",
"violet": "#ee82ee",
"wheat": "#f5deb3",
"white": "#ffffff",
"whitesmoke": "#f5f5f5",
"yellow": "#ffff00",
"yellowgreen": "#9acd32"
aliceblue: "#f0f8ff",
antiquewhite: "#faebd7",
aqua: "#00ffff",
aquamarine: "#7fffd4",
azure: "#f0ffff",
beige: "#f5f5dc",
bisque: "#ffe4c4",
black: "#000000",
blanchedalmond: "#ffebcd",
blue: "#0000ff",
blueviolet: "#8a2be2",
brown: "#a52a2a",
burlywood: "#deb887",
cadetblue: "#5f9ea0",
chartreuse: "#7fff00",
chocolate: "#d2691e",
coral: "#ff7f50",
cornflowerblue: "#6495ed",
cornsilk: "#fff8dc",
crimson: "#dc143c",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgoldenrod: "#b8860b",
darkgray: "#a9a9a9",
darkgreen: "#006400",
darkgrey: "#a9a9a9",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkseagreen: "#8fbc8f",
darkslateblue: "#483d8b",
darkslategray: "#2f4f4f",
darkslategrey: "#2f4f4f",
darkturquoise: "#00ced1",
darkviolet: "#9400d3",
deeppink: "#ff1493",
deepskyblue: "#00bfff",
dimgray: "#696969",
dimgrey: "#696969",
dodgerblue: "#1e90ff",
firebrick: "#b22222",
floralwhite: "#fffaf0",
forestgreen: "#228b22",
fuchsia: "#ff00ff",
gainsboro: "#dcdcdc",
ghostwhite: "#f8f8ff",
gold: "#ffd700",
goldenrod: "#daa520",
gray: "#808080",
green: "#008000",
greenyellow: "#adff2f",
grey: "#808080",
honeydew: "#f0fff0",
hotpink: "#ff69b4",
indianred: "#cd5c5c",
indigo: "#4b0082",
ivory: "#fffff0",
khaki: "#f0e68c",
lavender: "#e6e6fa",
lavenderblush: "#fff0f5",
lawngreen: "#7cfc00",
lemonchiffon: "#fffacd",
lightblue: "#add8e6",
lightcoral: "#f08080",
lightcyan: "#e0ffff",
lightgoldenrodyellow: "#fafad2",
lightgray: "#d3d3d3",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightsalmon: "#ffa07a",
lightseagreen: "#20b2aa",
lightskyblue: "#87cefa",
lightslategray: "#778899",
lightslategrey: "#778899",
lightsteelblue: "#b0c4de",
lightyellow: "#ffffe0",
lime: "#00ff00",
limegreen: "#32cd32",
linen: "#faf0e6",
magenta: "#ff00ff",
maroon: "#800000",
mediumaquamarine: "#66cdaa",
mediumblue: "#0000cd",
mediumorchid: "#ba55d3",
mediumpurple: "#9370db",
mediumseagreen: "#3cb371",
mediumslateblue: "#7b68ee",
mediumspringgreen: "#00fa9a",
mediumturquoise: "#48d1cc",
mediumvioletred: "#c71585",
midnightblue: "#191970",
mintcream: "#f5fffa",
mistyrose: "#ffe4e1",
moccasin: "#ffe4b5",
navajowhite: "#ffdead",
navy: "#000080",
oldlace: "#fdf5e6",
olive: "#808000",
olivedrab: "#6b8e23",
orange: "#ffa500",
orangered: "#ff4500",
orchid: "#da70d6",
palegoldenrod: "#eee8aa",
palegreen: "#98fb98",
paleturquoise: "#afeeee",
palevioletred: "#db7093",
papayawhip: "#ffefd5",
peachpuff: "#ffdab9",
peru: "#cd853f",
pink: "#ffc0cb",
plum: "#dda0dd",
powderblue: "#b0e0e6",
purple: "#800080",
rebeccapurple: "#663399",
red: "#ff0000",
rosybrown: "#bc8f8f",
royalblue: "#4169e1",
saddlebrown: "#8b4513",
salmon: "#fa8072",
sandybrown: "#f4a460",
seagreen: "#2e8b57",
seashell: "#fff5ee",
sienna: "#a0522d",
silver: "#c0c0c0",
skyblue: "#87ceeb",
slateblue: "#6a5acd",
slategray: "#708090",
slategrey: "#708090",
snow: "#fffafa",
springgreen: "#00ff7f",
steelblue: "#4682b4",
tan: "#d2b48c",
teal: "#008080",
thistle: "#d8bfd8",
tomato: "#ff6347",
turquoise: "#40e0d0",
violet: "#ee82ee",
wheat: "#f5deb3",
white: "#ffffff",
whitesmoke: "#f5f5f5",
yellow: "#ffff00",
yellowgreen: "#9acd32"
}.freeze
# Constructor. Inits to white (#FFFFFF) by default, or accepts any params
@ -355,7 +355,7 @@ module CanvasColor
# Convert to grayscale, using perception-based weighting
def grayscale
val = Color.new(self)
val.r = val.g = val.b = (0.2126 * val.r + 0.7152 * val.g + 0.0722 * val.b)
val.r = val.g = val.b = ((0.2126 * val.r) + (0.7152 * val.g) + (0.0722 * val.b))
val
end

View File

@ -57,7 +57,7 @@ module CanvasDynamoDB
tables[pair[0]] ||= []
tables[pair[0]] << pair[1]
end
sleep 2**@backoff_exp / 1000 if @backoff_exp > 0
sleep (2**@backoff_exp) / 1000 if @backoff_exp > 0
resp = @database.send(operation, { request_items: request_items(tables) })
responses << resp
until resp.send(unprocessed_attr).empty?

View File

@ -21,5 +21,5 @@ require 'active_support/all'
module CanvasExt
project_root = File.dirname(File.absolute_path(__FILE__))
Dir.glob(project_root + '/canvas_ext/*') { |file| require file }
Dir.glob(project_root + '/canvas_ext/*').sort.each { |file| require file }
end

View File

@ -149,7 +149,7 @@ module CanvasKaltura
sources = sources.sort_by do |a|
[a[:hasWarnings] || a[:isOriginal] != '0' ? CanvasSort::Last : CanvasSort::First,
a[:isOriginal] == '0' ? CanvasSort::First : CanvasSort::Last,
PREFERENCE.index(a[:fileExt]) || PREFERENCE.size + 1,
PREFERENCE.index(a[:fileExt]) || (PREFERENCE.size + 1),
a[:bitrate].to_i < suspicious_bitrate_threshold ? CanvasSort::First : CanvasSort::Last,
0 - a[:bitrate].to_i]
end

View File

@ -18,7 +18,6 @@
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
require 'thread'
require 'set'
module CanvasPandaPub

View File

@ -24,7 +24,7 @@ module CanvasPartman
max_id = base_class.maximum(base_class.partitioning_field)
return ensure_partitions(advance_partitions) if max_id.nil?
(0..max_id / base_class.partition_size + advance_partitions).each do |index|
(0..(max_id / base_class.partition_size) + advance_partitions).each do |index|
create_partition(index * base_class.partition_size, graceful: true)
end
end

View File

@ -198,7 +198,7 @@ describe CanvasPartman::Concerns::Partitioned do
expect(count_records("partman_trails")).to eq 1
expect(count_records("partman_trails_#{zoo.id / 5}")).to eq 1
expect(count_records("partman_trails_#{zoo.id / 5 + 1}")).to eq 0
expect(count_records("partman_trails_#{(zoo.id / 5) + 1}")).to eq 0
end
context 'via an association scope' do
@ -210,7 +210,7 @@ describe CanvasPartman::Concerns::Partitioned do
expect(count_records("partman_trails")).to eq 1
expect(count_records("partman_trails_#{zoo.id / 5}")).to eq 1
expect(count_records("partman_trails_#{zoo.id / 5 + 1}")).to eq 0
expect(count_records("partman_trails_#{(zoo.id / 5) + 1}")).to eq 0
expect(zoo.trails.count).to eq 1
expect(south.zoo).to eq zoo

View File

@ -40,10 +40,10 @@ File.join(File.dirname(__FILE__), 'canvas_quiz_statistics').tap do |cwd|
# spec support in support/
Dir.glob(File.join([
cwd, 'support', '**', '*.rb'
])).each { |file| require file }
])).sort.each { |file| require file }
# specs for shared metrics in analyzers/shared_metrics
Dir.glob(File.join([
cwd, 'analyzers', 'shared_metrics', '**', '*.rb'
])).each { |file| require file }
])).sort.each { |file| require file }
end

View File

@ -39,7 +39,7 @@ describe CanvasSlug do
end
it "prepends a provided purpose" do
expect(subject.generate("foobar")).to match /\Afoobar-\w{4}\z/
expect(subject.generate("foobar")).to match(/\Afoobar-\w{4}\z/)
end
end
end

View File

@ -22,12 +22,12 @@ module CanvasStringex
require "lucky_sneaks/unidecoder"
require "lucky_sneaks/acts_as_url"
String.send :include, LuckySneaks::StringExtensions
String.include LuckySneaks::StringExtensions
if defined?(ActiveRecord)
# Prevents uninitialized constant ActiveRecord::DatabaseConfigurations::ConnectionUrlResolver::URI
# (probably only relevant for specs in practice)
require 'uri'
ActiveRecord::Base.send :include, LuckySneaks::ActsAsUrl
ActiveRecord::Base.include LuckySneaks::ActsAsUrl
end
end

View File

@ -71,7 +71,7 @@ module DrDiff
path = path[git_dir.length..-1] if git_dir
severe = severe?(comment[:severity], severe_levels)
next unless heavy ||
severe && severe_anywhere ||
(severe && severe_anywhere) ||
diff.relevant?(path, comment[:position], severe: severe) ||
comment[:corrected]

View File

@ -277,7 +277,7 @@ module GoogleDrive
end
def file_extension_from_header(headers, entry)
file_extension = entry.extension && !entry.extension.empty? && entry.extension || 'unknown'
file_extension = (entry.extension && !entry.extension.empty? && entry.extension) || 'unknown'
if headers['content-disposition'] &&
headers['content-disposition'].match(/filename=[\"\']?[^;\"\'\.]+\.(?<file_extension>[^;\"\']+)[\"\']?/)

View File

@ -81,7 +81,7 @@ describe I18nliner::Extractors::RubyExtractor do
end
it "requires explicit keys if a key is provided and there is no scope" do
expect { extract("t 'foo', 'Foo'", I18nliner::Scope.root) }.to raise_error /ambiguous translation key/
expect { extract("t 'foo', 'Foo'", I18nliner::Scope.root) }.to raise_error(/ambiguous translation key/)
end
it "does not require explicit keys if the key is inferred and there is no scope" do
@ -95,7 +95,7 @@ describe I18nliner::Extractors::RubyExtractor do
context "sanitization" do
it "rejects stuff that looks sufficiently html-y" do
expect { extract "t 'dude', 'this is <em>important</em>'" }.to raise_error /html tags in default translation/
expect { extract "t 'dude', 'this is <em>important</em>'" }.to raise_error(/html tags in default translation/)
end
it "generallies be ok with angle brackets" do

View File

@ -47,6 +47,6 @@ module I18nTasks
end
end
Hash.send(:include, HashExtensions)
Hash.include HashExtensions
end
end

View File

@ -7,7 +7,7 @@ require 'shellwords'
namespace :i18n do
desc "Verifies all translation calls"
task :check => :i18n_environment do
Hash.send(:include, I18nTasks::HashExtensions) unless Hash.new.kind_of?(I18nTasks::HashExtensions)
Hash.include I18nTasks::HashExtensions unless Hash.new.kind_of?(I18nTasks::HashExtensions)
def I18nliner.manual_translations
I18n.available_locales
@ -105,8 +105,8 @@ namespace :i18n do
I18n.load_path += Dir[Rails.root.join('config', 'locales', 'locales.yml')]
I18n.load_path += Dir[Rails.root.join('config', 'locales', 'community.csv')]
I18n::Backend::Simple.send(:include, I18nTasks::CsvBackend)
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
I18n::Backend::Simple.include I18nTasks::CsvBackend
I18n::Backend::Simple.include I18n::Backend::Fallbacks
require 'i18nliner/extractors/translation_hash'
I18nliner::Extractors::TranslationHash.class_eval do
@ -118,7 +118,7 @@ namespace :i18n do
desc "Generates JS bundle i18n files (non-en) and adds them to assets.yml"
task :generate_js => :i18n_environment do
Hash.send(:include, I18nTasks::HashExtensions) unless Hash.new.kind_of?(I18nTasks::HashExtensions)
Hash.include I18nTasks::HashExtensions unless Hash.new.kind_of?(I18nTasks::HashExtensions)
locales = I18n.available_locales
all_translations = I18n.backend.send(:translations)
@ -188,7 +188,7 @@ namespace :i18n do
t = Time.now
translations = YAML.safe_load(open('config/locales/generated/en.yml'))
I18n.send :extend, I18nTasks::Lolcalize
I18n.extend I18nTasks::Lolcalize
lolz_translations = Hash.new
lolz_translations['lolz'] = process_lolz.call(translations['en'])
puts
@ -217,7 +217,7 @@ namespace :i18n do
desc "Exports new/changed English strings to be translated"
task :export => :environment do
Hash.send(:include, I18nTasks::HashExtensions) unless Hash.new.kind_of?(I18nTasks::HashExtensions)
Hash.include I18nTasks::HashExtensions unless Hash.new.kind_of?(I18nTasks::HashExtensions)
begin
base_filename = "config/locales/generated/en.yml"
@ -321,7 +321,7 @@ namespace :i18n do
desc "Validates and imports new translations"
task :import, [:source_file, :translated_file] => :environment do |t, args|
require 'open-uri'
Hash.send(:include, I18nTasks::HashExtensions) unless Hash.new.kind_of?(I18nTasks::HashExtensions)
Hash.include I18nTasks::HashExtensions unless Hash.new.kind_of?(I18nTasks::HashExtensions)
if args[:source_file]
source_translations = YAML.safe_load(open(args[:source_file]))
@ -401,7 +401,7 @@ namespace :i18n do
end
def autoimport(source_translations, new_translations)
Hash.send(:include, I18nTasks::HashExtensions) unless Hash.new.kind_of?(I18nTasks::HashExtensions)
Hash.include I18nTasks::HashExtensions unless Hash.new.kind_of?(I18nTasks::HashExtensions)
raise "Need source translations" unless source_translations
raise "Need translated_file" unless new_translations

View File

@ -65,7 +65,7 @@ module IncomingMailProcessor
# Raises anything the timeout method raises.
def with_timeout(&block)
method = @timeout_method || method(:default_timeout_method)
method.call &block
method.call(&block)
end
# Public: Wrap an object's methods in with_timeout calls. The original

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