diff options
author | lulalala <mark@goodlife.tw> | 2018-03-31 22:42:40 +0800 |
---|---|---|
committer | lulalala <mark@goodlife.tw> | 2019-03-31 22:59:12 +0800 |
commit | abee0343686b476139c476952b1c68f1fba6b3d0 (patch) | |
tree | cbc584a71167a90179a4c9515c69084f49cb3d28 /activemodel/lib | |
parent | 67d262f70f47154b2476b5fcadf21dd63ebc2597 (diff) | |
download | rails-abee0343686b476139c476952b1c68f1fba6b3d0.tar.gz rails-abee0343686b476139c476952b1c68f1fba6b3d0.tar.bz2 rails-abee0343686b476139c476952b1c68f1fba6b3d0.zip |
Raise deprecation for calling `[:f] = 'b'` or `[:f] << 'b'`
Revert some tests to ensure back compatibility
Diffstat (limited to 'activemodel/lib')
-rw-r--r-- | activemodel/lib/active_model/errors.rb | 50 |
1 files changed, 46 insertions, 4 deletions
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index 7c6346f577..5440988d27 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -302,11 +302,11 @@ module ActiveModel # person.errors.to_hash(true) # => {:name=>["name cannot be nil"]} def to_hash(full_messages = false) hash = {} - message_method = full_messages ? :full_message : :message + message_method = full_messages ? :full_messages_for : :messages_for group_by_attribute.each do |attribute, errors| - hash[attribute] = errors.map(&message_method) + hash[attribute] = public_send(message_method, attribute) end - hash + DeprecationHandlingMessageHash.new(hash, self) end alias :messages :to_hash @@ -458,7 +458,7 @@ module ActiveModel end def messages_for(attribute) - where(attribute).map(&:message).freeze + DeprecationHandlingMessageArray.new(where(attribute).map(&:message).freeze, self, attribute) end # Returns a full message for a given attribute. @@ -619,6 +619,48 @@ module ActiveModel end end + class DeprecationHandlingMessageHash < SimpleDelegator + def initialize(content, errors) + @errors = errors + super(content) + end + + def []=(attribute, value) + ActiveSupport::Deprecation.warn("Calling `[]=` to an ActiveModel::Errors is deprecated. Please call `ActiveModel::Errors#add` instead.") + + Array(value).each do |message| + @errors.add(attribute, message) + end + __setobj__ @errors.messages + value + end + + def [](attribute) + messages = super(attribute) + + return messages if messages + + __getobj__[attribute]= DeprecationHandlingMessageArray.new([], @errors, attribute) + end + end + + class DeprecationHandlingMessageArray < SimpleDelegator + def initialize(content, errors, attribute) + @errors = errors + @attribute = attribute + super(content) + end + + def <<(message) + ActiveSupport::Deprecation.warn("Calling `<<` to an ActiveModel::Errors message array in order to add an error is deprecated. Please call `ActiveModel::Errors#add` instead.") + + @errors.add(@attribute, message) + __setobj__ @errors[@attribute] + self + end + end + + # Raised when a validation cannot be corrected by end users and are considered # exceptional. # |