Skip to content

Instantly share code, notes, and snippets.

@coderberry
Created November 9, 2011 16:19
Show Gist options
  • Select an option

  • Save coderberry/1351951 to your computer and use it in GitHub Desktop.

Select an option

Save coderberry/1351951 to your computer and use it in GitHub Desktop.
application_helper.rb
module ApplicationHelper
# Helper method to wrap an input field for twitter bootstrap
# @param [Object] model_instance Instanciated model
# @param [Symbol] field_name Attribute name of the field being referred to in this block
# @param [Hash] options Set of options. See example.
#
# @example
# <!--
# Available options:
# :required [Boolean] show the 'required' asterisk (true | false)
# :help [String] default help text to show below the field
# -->
#
# <!-- @person is an instanciated Person -->
# <%= field_wrapper(@person, :first_name, {:required => true, :help => "first name of person"}) do %>
# <%= f.text_field :first_name, :size => 30, :type => "text", :class => "xlarge" %>
# <% end %>
#
# <!-- should return the following -->
# <div class="clearfix">
# <label for="person_first_name">
# <span class="required">*</span>
# First Name
# </label>
# <div class="input">
# <input type="text" name="person[first_name]" id="person_first_name" class="xlarge" size="30" />
# <span class="help-block">
# first name of person
# </span>
# </div>
# </div>
#
def field_wrapper(model_instance, field_name, options={}, &block)
content = capture(&block) # capture the contents of the block
field_id = model_instance.class.name.underscore
# Determine the classes for the outer div wrapper
classes = ["clearfix"]
classes << "error" if model_instance.errors[field_name].any?
content_tag(:div, :class => classes.join(' ')) do
content_tag(:label, :for => "#{field_id}_#{field_name}") do
# Determine if the field is required
if options[:required] == true
content_tag(:span, "*", :class => "required")
end
field_name.to_s.humanize.titleize
end +
content_tag(:div, :class => "input") do
content +
if model_instance.errors[field_name].any?
content_tag(:span, :class => "help-block") do
model_instance.errors[field_name].join(', ')
end
else
if options[:help].present?
content_tag(:span, :class => "help-block") do
options[:help]
end
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment