lib/reform/form/active_model/validations.rb in reform-rails-0.2.0.rc2 vs lib/reform/form/active_model/validations.rb in reform-rails-0.2.0.rc3

- old
+ new

@@ -50,16 +50,28 @@ # and second to expose errors for presentation. def errors(*args) @amv_errors end + def custom_errors + # required to keep update the ActiveModel::Errors#details used to test for + # added errors ActiveModel::Errors#added? and needs to be inside this block! + super.each do |custom_error| + errors = custom_error.errors + # CustomError build always the errors with an hash where the value is an array + errors.values.first.each do |value| + @amv_errors.add(errors.keys.first, value) + end + end + end + def validate!(params, pointers=[]) @amv_errors = ActiveModel::Errors.new(self) super.tap do # @fran: super ugly hack thanks to the shit architecture of AMV. let's drop it in 3.0 and move on! - all_errors = @result.instance_variable_get(:@results) + all_errors = @result.to_results nested_errors = @result.instance_variable_get(:@failure) @result = Reform::Contract::Result.new(all_errors, [nested_errors].compact) @amv_errors = Result::ResultErrors.new(@result, self, @result.success?, @amv_errors) @@ -119,19 +131,39 @@ def empty? @success end def [](k) - super || [] + super(k.to_sym) || [] end # rails expects this to return a stringified hash of the messages def to_s messages.to_s end + def add(key, error_text) + # use rails magic to get the correct error_text and make sure we still update details and fields + text = @amv_errors.add(key, error_text) + + # using error_text instead of text to either keep the symbol which will be + # magically replaced with the translate or directly the string - this is also + # required otherwise in the custom_errors method we will add the actual message in the + # ActiveModel::Errors#details which is not correct if a symbol was passed here + Reform::Contract::CustomError.new(key, error_text, @result.to_results) + + # but since messages method is actually already defined in `Reform::Contract::Result::Errors + # we need to update the @dotted_errors instance variable to add or merge a new error + @dotted_errors.key?(key) ? @dotted_errors[key] |= text : @dotted_errors[key] = text + instance_variable_set(:@dotted_errors, @dotted_errors) + end + def method_missing(m, *args, &block) @amv_errors.send(m, *args, &block) # send all methods to the AMV errors, even privates. + end + + def respond_to?(method) + @amv_errors.respond_to?(method) ? true : super end end end # Validator is the validatable object. On the class level, we define validations,