Detect label and value automatically.

This commit is contained in:
José Valim 2009-12-10 00:22:53 -02:00
parent af89e090f2
commit d9cc0a3f94
6 changed files with 31 additions and 14 deletions

View File

@ -5,7 +5,6 @@
* Sample CSS
* Test forms with non objects
* Get default string options from column definition
* Detect label and values automatically
* Add support to default :prompt methods on datetime inputs
* Add support to default label method
* Add wrapper support

View File

@ -18,4 +18,12 @@ module SimpleForm
SimpleForm::Components::Label, SimpleForm::Components::Input,
SimpleForm::Components::Hint, SimpleForm::Components::Error
]
# Series of attemps to detect a default label method for collection
mattr_accessor :collection_label_methods
@@collection_label_methods = [ :name, :title, :to_s ]
# Series of attemps to detect a default value method for collection
mattr_accessor :collection_value_methods
@@collection_value_methods = [ :id, :to_s ]
end

View File

@ -57,19 +57,19 @@ module SimpleForm
end
def detect_collection_methods(collection, options)
case collection.first
sample = collection.first || collection.last
case sample
when Array
label, value = :first, :last
when Integer
value = :to_i
when String
# Do nothing ...
else
# TODO Implement detection logic
label, value = :to_s, :to_i
when String, NilClass
label, value = :to_s, :to_s
end
options[:label_method] ||= label || :to_s
options[:value_method] ||= value || :to_s
options[:label_method] ||= label || SimpleForm.collection_label_methods.find { |m| sample.respond_to?(m) }
options[:value_method] ||= value || SimpleForm.collection_value_methods.find { |m| sample.respond_to?(m) }
end
end
end

View File

@ -190,6 +190,13 @@ class InputTest < ActionView::TestCase
assert_no_select 'select option[value=]', ""
end
test 'input should detect label and value on collections' do
users = [ setup_new_user(:id => 1, :name => "Jose"), setup_new_user(:id => 2, :name => "Carlos") ]
with_input_for :description, :select, :collection => users
assert_select 'select option[value=1]', 'Jose'
assert_select 'select option[value=2]', 'Carlos'
end
test 'input should allow overriding collection for radio types' do
with_input_for :name, :radio, :collection => ['Jose', 'Carlos']
assert_select 'input[type=radio][value=Jose]'

View File

@ -10,9 +10,11 @@ class Column
end
class User < OpenStruct
attr_reader :id
def id
1
def initialize(attributes={})
@id = attributes.delete(:id)
super
end
def new_record?

View File

@ -32,12 +32,13 @@ class ActionView::TestCase
@response = MockResponse.new(self)
end
def setup_new_user
@user = User.new(
def setup_new_user(options={})
@user = User.new({
:id => 1,
:name => 'New in Simple Form!',
:description => 'Hello!',
:created_at => Time.now
)
}.merge(options))
end
def protect_against_forgery?