Module: Sinatra::OhmErrorHelpers

Defined in:
lib/sinatra/support/errorhelpers.rb,
lib/sinatra/support/ohmerrorhelpers.rb

Overview

Ohm error helpers.

# Only for those who use Ohm and HAML.
require 'ohm'
require 'haml'

require 'sinatra/support/ohmerrorhelpers'

class Main < Sinatra::Base
  helpers Sinatra::OhmErrorHelpers
end

Common usage

- errors_on @user do |e|
  - e.on [:email, :not_present], "We need your email address."
  - e.on [:password, :not_present], "You must specify a password."

This produces the following:

<div class="errors">
  <ul>
    <li>We need your email address</li>
    <li>You must specify a password.</li>
  </ul>
</div>

Defined Under Namespace

Classes: HamlErrorPresenter

Instance Method Summary collapse

Instance Method Details

#errors_on(object, options = { :class => 'errors' }) {|Sinatra::Support::HamlErrorPresenter| ... } ⇒ Object

Presents errors on your form. Takes the explicit approach and assumes that for every form you have, the copy for the errors are important, instead of producing canned responses.

Parameters:

  • object (#errors)

    An object responding to #errors. This validation also checks for the presence of a #full_messages method in the errors object for compatibility with ActiveRecord style objects.

  • options (Hash) (defaults to: { :class => 'errors' })

    a hash of HTML attributes to place on the containing div.

Options Hash (options):

  • :class (#to_s) — default: defaults to errors

    The css class to put in the div.

Yields:

  • (Sinatra::Support::HamlErrorPresenter)

    an object responding to #on.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/sinatra/support/errorhelpers.rb', line 45

def errors_on(object, options = { :class => 'errors' }, &block)
  return if object.errors.empty?

  lines = if object.errors.respond_to?(:full_messages)
    object.errors.full_messages
  else
    HamlErrorPresenter.new(object.errors).present(self, &block)
  end

  haml_tag(:div, options) do
    haml_tag(:ul) do
      lines.each do |error|
        haml_tag(:li, error)
      end
    end
  end
end