Skip to content

Instantly share code, notes, and snippets.

@victorgiraldes
Created December 10, 2019 13:42
Show Gist options
  • Save victorgiraldes/5febfdcf4e078c05062d71d58883fb12 to your computer and use it in GitHub Desktop.
Save victorgiraldes/5febfdcf4e078c05062d71d58883fb12 to your computer and use it in GitHub Desktop.
# Classe base de validações auxiliares
class BaseValidator < SimpleDelegator
include ActiveModel::Model
include ActiveModel::Validations
def build_error_list(prefix, list, indexes = nil)
error_list = list.each_with_index.map do |item, i|
index = coalesce_index(item, i, indexes)
key = [prefix, index].compact.join '.'
[key, item.errors.messages] if item.errors.any?
end.compact
Hash[error_list]
end
private
def coalesce_index(item, index, indexes)
return indexes[i] if indexes.present?
item.respond_to?(:index) ? item.index : index
end
class << self
def i18n_scope
const_defined?(:MODEL) ? self::MODEL.i18n_scope : super
end
def model_name
const_defined?(:MODEL) ? self::MODEL.model_name : super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment