heartcombo--simple_form/lib/simple_form/form_builder.rb

82 lines
2.4 KiB
Ruby
Raw Normal View History

require 'simple_form/label'
require 'simple_form/input'
require 'simple_form/hint'
2009-12-08 13:38:03 -05:00
require 'simple_form/error'
2009-12-09 12:48:40 -05:00
require 'simple_form/map_type'
2009-12-09 13:03:04 -05:00
require 'simple_form/i18n_cache'
2009-11-18 18:50:43 -05:00
module SimpleForm
class FormBuilder < ActionView::Helpers::FormBuilder
include SimpleForm::Label
include SimpleForm::Input
include SimpleForm::Hint
2009-12-08 13:38:03 -05:00
include SimpleForm::Error
2009-11-19 16:26:16 -05:00
2009-12-09 12:48:40 -05:00
extend SimpleForm::MapType
2009-12-09 13:03:04 -05:00
extend SimpleForm::I18nCache
2009-12-09 12:48:40 -05:00
map_type :boolean, :to => :check_box
map_type :text, :to => :text_area
map_type :datetime, :to => :datetime_select, :options => true
map_type :date, :to => :date_select, :options => true
map_type :time, :to => :time_select, :options => true
map_type :password, :to => :password_field
map_type :hidden, :to => :hidden_field
map_type :select, :to => :collection_select, :options => true, :collection => true
map_type :radio, :to => :collection_radio, :collection => true
map_type :numeric, :to => :text_field
map_type :string, :to => :text_field
2009-11-19 16:26:16 -05:00
def input(attribute, options={})
2009-12-08 09:55:04 -05:00
@attribute, @options = attribute, options
2009-12-09 11:55:29 -05:00
@options.assert_valid_keys(:as, :label, :required, :hint, :options, :html,
:collection, :label_method, :value_method)
@input_type = (@options[:as] || default_input_type).to_sym
2009-12-08 08:48:31 -05:00
2009-12-08 09:55:04 -05:00
label = generate_label
input = generate_input
hint = generate_hint
2009-12-08 13:38:03 -05:00
error = generate_error
2009-12-08 08:48:31 -05:00
2009-12-08 13:38:03 -05:00
label << input << hint << error
2009-11-19 16:26:16 -05:00
end
private
def required_class
'required' if attribute_required?
end
def attribute_required?
@options[:required] != false
end
def default_css_classes(merge_class=nil)
"#{@input_type} #{required_class} #{merge_class}".strip
end
def default_input_type
column = @object.column_for_attribute(@attribute)
input_type = column.type
case input_type
2009-12-09 12:32:15 -05:00
when :decimal, :integer then :numeric
when :timestamp then :datetime
when nil, :string then
@attribute.to_s =~ /password/ ? :password : :string
else input_type
end
end
2009-12-08 14:08:36 -05:00
def hidden_input?
@input_type == :hidden
end
2009-12-08 14:08:36 -05:00
def translate_form(scope, default='')
lookups = [:"#{@object_name}.#{@attribute}", :"#{@attribute}", default]
I18n.t(lookups.shift, :scope => :"simple_form.#{scope}", :default => lookups)
2009-12-08 14:08:36 -05:00
end
2009-11-18 18:50:43 -05:00
end
end