Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Output
- <input type="text" size="30" name="#<MonitoringTemplate:0x2aaaaf2832a8>[name]" id="__MonitoringTemplate:0x2aaaaf2832a8_name" class="text"/>
- ## View
- <%= field_for :monitoring_template, :name %>
- ## Controller
- def new
- @monitoring_template = MonitoringTemplate.new
- end
- ## Helpers
- # Displays a label, field, and error message (if available) for the specified object/method pair.
- #
- # *Valid Options*
- # :label => "The label to use" # Defaults to humanized method name
- # :type => :text_field # A method which accepts object_name, method, and field_options. See
- # # ActionView::Helpers::FormHelper, ActionView::Helpers::FormOptionsHelper etc.
- # :float => false # If true, the field will be wrapped in a div with the floating_input class.
- #
- # The field_options hash will be passed to the FormHelper method intact.
- #
- # If a block is provided to field_proc it will be used to build the field.
- def field_for(object_name, method, options = {}, field_options = {}, &field_proc)
- options[:label] ||= method.to_s.titlecase
- options[:type] ||= :text_field
- options[:float] ||= false
- label = content_tag("label", options[:label], :for => "#{object_name}_#{method}")
- obj = get_object_from_string(object_name)
- unless block_given?
- # Call the requested method
- field = self.send(options[:type], obj, method, field_options)
- else
- field = field_proc.call(obj)
- end
- errors = error_message_on(object_name, method, options[:label] + " ")
- if options[:type] == :check_box
- fieldset = content_tag("div", field + " " + label + errors, :class => "checkbox_group")
- else
- fieldset = label + field + errors
- end
- fieldset = content_tag("div", fieldset, :class => "floating_input") if options[:float]
- return fieldset
- end
- def get_object_from_string(object_name)
- if object_name.is_a?(String) || object_name.is_a?(Symbol)
- obj = instance_variable_get("@#{object_name}")
- raise ArgumentError.new("Invalid object name #{object_name} provided to get_object_from_string") if obj.nil?
- else
- obj = object_name
- end
- return obj
- end
Add Comment
Please, Sign In to add comment