Skip to content

Instantly share code, notes, and snippets.

@linojon
Created October 3, 2009 14:47
Show Gist options
  • Save linojon/200670 to your computer and use it in GitHub Desktop.
Save linojon/200670 to your computer and use it in GitHub Desktop.
# code borrowed error_messages_for
def error_counts_for(*params)
#debugger
options = params.extract_options!.symbolize_keys
if object = options.delete(:object)
objects = [object].flatten
else
objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
end
#count = objects.inject(0) {|sum, object| sum + (object.errors.count.zero? ? 0 : 1) }
# total for each object, get count of fields with errors (uniq keys)
count = objects.inject(0) { |sum, object| sum +
object.errors.collect { |k,v| k }.uniq.size
}
unless count.zero?
options[:object_name] ||= params.first
options[:header_message] = "Oops, #{pluralize(count, 'error')} prevented this #{options[:object_name].to_s.gsub('_', ' ')} from being saved" unless options.include?(:header_message)
#options[:message] ||= 'There were problems with the following fields:' unless options.include?(:message)
options[:message] ||= 'Please correct and try again' unless options.include?(:message)
base_messages = objects.map {|object| content_tag :p, object.errors[:base] unless object.errors[:base].blank? }
field_messages = objects.map {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }
contents = ''
contents << content_tag(options[:header_tag] || :h2, options[:header_message]) unless options[:header_message].blank?
contents << content_tag(:p, options[:message]) unless options[:message].blank?
contents << base_messages.to_s
contents << content_tag(:ul, field_messages)
content_tag(:div, contents, :class => 'errorExplanation')
else
''
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment