2020-10-27 00:50:13 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2011-11-08 01:06:01 +08:00
|
|
|
#
|
2017-04-28 04:01:09 +08:00
|
|
|
# Copyright (C) 2011 - present Instructure, Inc.
|
2011-11-08 01:06:01 +08:00
|
|
|
#
|
|
|
|
# This file is part of Canvas.
|
|
|
|
#
|
|
|
|
# Canvas is free software: you can redistribute it and/or modify it under
|
|
|
|
# the terms of the GNU Affero General Public License as published by the Free
|
|
|
|
# Software Foundation, version 3 of the License.
|
|
|
|
#
|
|
|
|
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
|
|
|
|
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
|
|
|
|
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
|
|
# details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Affero General Public License along
|
|
|
|
# with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
#
|
|
|
|
|
|
|
|
module CustomValidations
|
|
|
|
module ClassMethods
|
2016-08-23 06:05:03 +08:00
|
|
|
def validates_as_url(*fields, allowed_schemes: %w[http https])
|
2012-05-05 04:16:03 +08:00
|
|
|
validates_each(fields, allow_nil: true) do |record, attr, value|
|
2021-10-20 05:23:50 +08:00
|
|
|
value, = CanvasHttp.validate_url(value, allowed_schemes: allowed_schemes)
|
2014-03-20 23:52:26 +08:00
|
|
|
|
2012-05-05 04:16:03 +08:00
|
|
|
record.send("#{attr}=", value)
|
2019-09-24 22:50:17 +08:00
|
|
|
rescue CanvasHttp::Error, URI::Error, ArgumentError
|
2012-05-05 04:16:03 +08:00
|
|
|
record.errors.add attr, "is not a valid URL"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def validates_as_readonly(*fields)
|
2021-10-23 03:50:42 +08:00
|
|
|
validates_each(fields) do |record, attr, _value|
|
2012-05-05 04:16:03 +08:00
|
|
|
if !record.new_record? && record.send("#{attr}_changed?")
|
|
|
|
record.errors.add attr, "cannot be changed"
|
2011-11-08 01:06:01 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-06-07 01:51:49 +08:00
|
|
|
# alloweds is a hash of old_value => [new_value]
|
|
|
|
# on update, only those transitions will be allowed for the given field
|
|
|
|
def validates_allowed_transitions(field, alloweds)
|
|
|
|
validates_each(field) do |record, attr, value|
|
|
|
|
if !record.new_record? && record.send("#{attr}_changed?")
|
|
|
|
old_val = record.send("#{attr}_was")
|
|
|
|
unless alloweds.any? { |old, news| old_val == old && Array(news).include?(value) }
|
|
|
|
record.errors.add attr, "cannot be changed to that value"
|
|
|
|
end
|
2012-05-30 06:55:40 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2011-11-08 01:06:01 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.included(klass)
|
|
|
|
if klass < ActiveRecord::Base
|
|
|
|
klass.send :extend, ClassMethods
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|