Skip to content

Instantly share code, notes, and snippets.

@nacengineer
Last active October 2, 2015 18:58
Show Gist options
  • Save nacengineer/2301097 to your computer and use it in GitHub Desktop.
Save nacengineer/2301097 to your computer and use it in GitHub Desktop.
A little snippet to add to application_helper to handle errors in a rails 3.2 form. (requires HAML 4). This allows you to replace the generated error explanation at the top of your _form.haml partials
# create this in helpers/feedback_helper.rb
# use version 1 for haml (buggy) or version 2 for erb
# version 1 via haml
require 'haml'
module FeedbackHelper
def self.included(base)
base.class_eval do
include Haml::Helpers
extend Haml::Helpers
end
end
def explain_errors( model )
init_haml_helpers
if model.present? && model.errors.any?
capture_haml do
haml_tag :h4 do
haml_concat <<-HERE_DOC
#{pluralize( model.errors.count, "error")} prohibited this
#{ model.class } from being saved:
HERE_DOC
end
haml_tag :ul do
model.errors.full_messages.each do |msg|
haml_tag :li, msg
end
end
end
end
end
end
# version 2 less buggy as its erb
module FeedbackHelper
# ERB ONLY
def explain_errors(model)
if model.present? && model.errors.any?
html = ""
html << content_tag(:h4) do
<<-HERE_DOC
#{pluralize( model.errors.count, "error")} prohibited this
#{ model.class } from being saved:
HERE_DOC
end
html << content_tag(:ul) do
model.errors.full_messages.each {|msg|
concat(content_tag(:li, msg, class: 'text-error'))
}
end
html.html_safe
end
end
end
# leverage this in your haml _form.haml partial with
= simple_form_for @object do |f|
= explain_errors @object
...
@nacengineer
Copy link
Author

fixed for haml 4

@nacengineer
Copy link
Author

ugh. still broken. lol

@nacengineer
Copy link
Author

the erb one works. the other one sometimes needs init_haml_helpers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment