Make Error a component.

This commit is contained in:
José Valim 2009-12-09 16:55:39 -02:00
parent 02775cf878
commit 9699bca5a8
3 changed files with 48 additions and 17 deletions

View File

@ -0,0 +1,32 @@
module SimpleForm
class AbstractComponent
attr_reader :builder, :attribute, :input_type, :options
def initialize(builder, attribute, input_type, options)
@builder = builder
@attribute = attribute
@input_type = input_type
@options = options
end
def generate
(valid? ? content : nil).to_s
end
def valid?
true
end
def template
@builder.template
end
def object
@builder.object
end
def hidden_input?
@input_type == :hidden
end
end
end

View File

@ -1,20 +1,15 @@
module SimpleForm
module Error
class Error < AbstractComponent
def valid?
!hidden_input? && !errors.blank?
end
private
def errors
@errors ||= object.errors[@attribute]
end
def generate_error
return '' if skip_error? || (errors = find_errors).blank?
errors = errors.to_sentence if errors.respond_to?(:to_sentence)
@template.content_tag(:span, errors, :class => 'error')
end
def skip_error?
hidden_input?
end
def find_errors
@object.errors[@attribute]
end
def content
template.content_tag(:span, Array(errors).to_sentence, :class => 'error')
end
end
end

View File

@ -1,3 +1,5 @@
require 'simple_form/abstract_component'
require 'simple_form/label'
require 'simple_form/input'
require 'simple_form/hint'
@ -7,10 +9,12 @@ require 'simple_form/i18n_cache'
module SimpleForm
class FormBuilder < ActionView::Helpers::FormBuilder
# Make the template accessible for components
attr_reader :template
include SimpleForm::Label
include SimpleForm::Input
include SimpleForm::Hint
include SimpleForm::Error
extend SimpleForm::MapType
extend SimpleForm::I18nCache
@ -37,7 +41,7 @@ module SimpleForm
label = generate_label
input = generate_input
hint = generate_hint
error = generate_error
error = Error.new(self, @attribute, @input_type, @options).generate
label << input << hint << error
end