I see myself writing a lot of :size => nil for f.text_field as so:
<%= f.text_field :street_address, :size => nil %>
<%= f.text_field :post_code, :size => nil %>
<%= f.text_field :city, :size => nil %>
Which is just dumb. Without the :size => nil above, text_field renders an <input> with a size="some number" (usually size="30") which I don't need or want there.
So, how can I implement DRY and make it so that f.text_field would not generate the size=30 or size="some number" attribute by default? This way I can avoid always having to type :size => nil.
All default field options are stored in one hash. It defaults to the following:
# action_view/helpers/form_helper
DEFAULT_FIELD_OPTIONS = { "size" => 30 }
You can delete "size" from it in an initializer, for example.
ActionView::Helpers::InstanceTag::DEFAULT_FIELD_OPTIONS.delete("size")
Rails extends Object class with with_options method. You can take advantage of it:
<%= form_for :foo do |f| %>
<% f.with_options :size => nil do |f_nil| %>
<%= f_nil.text_field :street_address %>
<%= f_nil.text_field :post_code %>
<%= f.text_field :city %> <!-- you can use old f here too! -->
<% end %>
<% end %>
Gives:
<input id="foo_street_address" name="foo[street_address]" type="text" />
<input id="foo_post_code" name="foo[post_code]" type="text" />
<input id="foo_city" name="foo[city]" size="30" type="text" /> <!-- you can use old f here too! -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With