diff options
author | lulalala <mark@goodlife.tw> | 2018-03-15 16:13:18 +0800 |
---|---|---|
committer | lulalala <mark@goodlife.tw> | 2019-03-31 22:59:12 +0800 |
commit | ef68d3e35cb58f9f491993eeec6e7de99442dd06 (patch) | |
tree | 04da4aac2ecb80d9c0a7aa170c4110b29308a8b8 /activemodel/lib/active_model/error.rb | |
parent | db0256cad7487e7b8cc5f0640e0c8144d6b5d23f (diff) | |
download | rails-ef68d3e35cb58f9f491993eeec6e7de99442dd06.tar.gz rails-ef68d3e35cb58f9f491993eeec6e7de99442dd06.tar.bz2 rails-ef68d3e35cb58f9f491993eeec6e7de99442dd06.zip |
Add ActiveModel::Error and NestedError
Add initialize_dup to deep dup.
Move proc eval and flexible message position out to Errors,
because proc eval is needed for Errors#added? and Errors#delete
Diffstat (limited to 'activemodel/lib/active_model/error.rb')
-rw-r--r-- | activemodel/lib/active_model/error.rb | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/activemodel/lib/active_model/error.rb b/activemodel/lib/active_model/error.rb new file mode 100644 index 0000000000..214a0b356d --- /dev/null +++ b/activemodel/lib/active_model/error.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +module ActiveModel + # == Active \Model \Error + # + # Represents one single error + class Error + CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict] + MESSAGE_OPTIONS = [:message] + + def initialize(base, attribute, type, **options) + @base = base + @attribute = attribute + @raw_type = type + @type = type || :invalid + @options = options + end + + def initialize_dup(other) + @attribute = @attribute.dup + @raw_type = @raw_type.dup + @type = @type.dup + @options = @options.deep_dup + end + + attr_reader :base, :attribute, :type, :raw_type, :options + + def message + case raw_type + when Symbol + base.errors.generate_message(attribute, raw_type, options.except(*CALLBACKS_OPTIONS)) + else + raw_type + end + end + + def detail + { error: raw_type }.merge(options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS)) + end + + def full_message + base.errors.full_message(attribute, message) + end + + # See if error matches provided +attribute+, +type+ and +options+. + def match?(attribute, type = nil, **options) + if @attribute != attribute || (type && @type != type) + return false + end + + options.each do |key, value| + if @options[key] != value + return false + end + end + + true + end + end +end |