Permalink
Browse files

Use check_box_checked? from Rails for boolean inputs

  • Loading branch information...
1 parent 44a9cc3 commit a2d6a09fe6b5be2f98a99f8bc70df8f7db3d36d7 @eugenebolshakov eugenebolshakov committed Jan 14, 2011
Showing with 24 additions and 1 deletion.
  1. +2 −1 lib/formtastic.rb
  2. +22 −0 spec/inputs/boolean_input_spec.rb
View
3 lib/formtastic.rb
@@ -1256,12 +1256,13 @@ def boolean_input(method, options)
html_options = options.delete(:input_html) || {}
checked_value = options.delete(:checked_value) || '1'
unchecked_value = options.delete(:unchecked_value) || '0'
+ checked = @object && ActionView::Helpers::InstanceTag.check_box_checked?(@object.send(:"#{method}"), checked_value)
html_options[:id] = html_options[:id] || generate_html_id(method, "")
input = template.check_box_tag(
"#{@object_name}[#{method}]",
checked_value,
- (@object && @object.send(:"#{method}")),
+ checked,
html_options
)
View
22 spec/inputs/boolean_input_spec.rb
@@ -83,6 +83,28 @@
output_buffer.should_not have_tag('form li label input[@type="hidden"]') # invalid HTML5
end
+ it 'should generate a checked input if object.method returns checked value' do
+ @new_post.stub!(:allow_comments).and_return('yes')
+
+ form = semantic_form_for(@new_post) do |builder|
+ concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'yes', :unchecked_value => 'no'))
+ end
+
+ output_buffer.concat(form) if Formtastic::Util.rails3?
+ output_buffer.should have_tag('form li label input[@type="checkbox"][@value="yes"][@checked="checked"]')
+ end
+
+ it 'should not generate a checked input if object.method returns unchecked value' do
+ @new_post.stub!(:allow_comments).and_return('no')
+
+ form = semantic_form_for(@new_post) do |builder|
+ concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'yes', :unchecked_value => 'no'))
+ end
+
+ output_buffer.concat(form) if Formtastic::Util.rails3?
+ output_buffer.should have_tag('form li label input[@type="checkbox"][@value="yes"]:not([@checked])')
+ end
+
it 'should generate a label and a checkbox even if no object is given' do
form = semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:allow_comments, :as => :boolean))

0 comments on commit a2d6a09

Please sign in to comment.