1
0
Fork 0
mirror of https://github.com/heartcombo/simple_form.git synced 2022-11-09 12:19:26 -05:00

Adding errors to inputs.

This commit is contained in:
Carlos Antonio da Silva 2009-12-08 16:38:03 -02:00
parent 97276d6e2c
commit 27e3e38c05
4 changed files with 62 additions and 1 deletions

12
lib/simple_form/error.rb Normal file
View file

@ -0,0 +1,12 @@
module SimpleForm
module Error
private
def generate_error
return '' unless errors = @object.errors[@attribute]
errors = errors.is_a?(Array) ? errors.to_sentence : errors
@template.content_tag(:span, errors, :class => 'error')
end
end
end

View file

@ -1,12 +1,14 @@
require 'simple_form/label'
require 'simple_form/input'
require 'simple_form/hint'
require 'simple_form/error'
module SimpleForm
class FormBuilder < ActionView::Helpers::FormBuilder
include SimpleForm::Label
include SimpleForm::Input
include SimpleForm::Hint
include SimpleForm::Error
def input(attribute, options={})
@attribute, @options = attribute, options
@ -17,8 +19,9 @@ module SimpleForm
label = generate_label
input = generate_input
hint = generate_hint
error = generate_error
label << input << hint
label << input << hint << error
end
private

33
test/error_test.rb Normal file
View file

@ -0,0 +1,33 @@
require 'test_helper'
class ErrorTest < ActionView::TestCase
def setup
@super_user = SuperUser.new
end
test 'input should not generate error by default' do
simple_form_for @user do |f|
concat f.input :name
end
assert_no_select 'form span.error'
end
test 'input should generate error messages for attributes with a single error' do
simple_form_for @super_user do |f|
concat f.input :name
concat f.input :description
end
assert_select 'form span.error', "can't be blank"
assert_select 'form span.error', "must be longer than 15 characters"
end
test 'input should generate error messages for attributes with several errors' do
simple_form_for @super_user do |f|
concat f.input :age
concat f.input :credit_limit
end
assert_select 'form span.error', "is not a number and must be greater than 18"
assert_select 'form span.error', "must be present and must be greater than 0"
end
end

View file

@ -27,6 +27,10 @@ class User < OpenStruct
def human_attribute_name(attribute)
nil
end
def errors
{}
end
end
class SuperUser < User
@ -37,4 +41,13 @@ class SuperUser < User
else super
end
end
def errors
@errors ||= {
:name => "can't be blank",
:description => "must be longer than 15 characters",
:age => ["is not a number", "must be greater than 18"],
:credit_limit => ["must be present", "must be greater than 0"]
}
end
end