Class: ValidatesStructure::Validator::EnumerableValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validates-structure.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, values) ⇒ Object

Validates each value in an enumerable class using ActiveModel validations. Adapted from a snippet by Milovan Zogovic (stackoverflow.com/a/12744945)



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/validates-structure.rb', line 178

def validate_each(record, attribute, values)
  return unless values.respond_to?(:each_with_index)
  values.each_with_index do |value, index|
    options.each do |key, args|
      validator_options = { attributes: attribute }
      validator_options.merge!(args) if args.is_a?(Hash)

      next if value.nil? && validator_options[:allow_nil]
      next if value.blank? && validator_options[:allow_blank]
      next if key.to_s == "allow_nil"
      next if key.to_s == "allow_blank"

      validator_class_name = "#{key.to_s.camelize}Validator"
      validator_class = self.class.parent.const_get(validator_class_name)
      validator = validator_class.new(validator_options)

      # TODO: There should be a better way!
      tmp_record = record.dup
      validator.validate_each(tmp_record, attribute, value)
      tmp_record.errors.each do |nested_attribute, error|
        indexed_attribute = nested_attribute.to_s.sub(/^#{attribute}/, "#{attribute}[#{index}]")
        record.errors.add(indexed_attribute, error)
      end
    end
  end
end