Sha256: b8e314e4f27621c2c60950cf44f38cf2efefe733a6bcc90aec29b1298fa40eb6

Contents?: true

Size: 1.18 KB

Versions: 2

Compression:

Stored size: 1.18 KB

Contents

module PhModel
  module Concerns
    module AttributeNestedValidation
      extend ActiveSupport::Concern

      included do |other|
        other.validate :validate_nested_attributes
      end

      def validate_nested_attributes
        self.class.attributes.each do |attribute_name, info|
          value = send(attribute_name)
          if info[:type].is_a? Array
            if value.respond_to? :each_with_index
              value.each_with_index do |item_value, index|
                check_one(item_value, format_nested_attribute_name(attribute_name, index, item_value))
              end
            end
          else
            check_one(value, attribute_name)
          end
        end
      end

      def format_nested_attribute_name(attribute_name, index, item_value)
        "#{attribute_name}[#{index}]"
      end

      def check_one(value, attribute_name)
        return if !value.respond_to?(:valid?) || !value.respond_to?(:errors) || value.errors.nil? ||
          (value.respond_to?(:frozen?) && value.frozen?) || value.valid?
        value.errors.full_messages.each do |message|
          errors.add(:base, "#{attribute_name}.#{message}")
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ph_model-1.2.0 lib/ph_model/concerns/attribute_nested_validation.rb
ph_model-1.1.3 lib/ph_model/concerns/attribute_nested_validation.rb