Guest User

Untitled

a guest
Mar 13th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. ## Output
  2. <input type="text" size="30" name="#<MonitoringTemplate:0x2aaaaf2832a8>[name]" id="__MonitoringTemplate:0x2aaaaf2832a8_name" class="text"/>
  3.  
  4. ## View
  5. <%= field_for :monitoring_template, :name %>
  6.  
  7. ## Controller
  8. def new
  9. @monitoring_template = MonitoringTemplate.new
  10. end
  11.  
  12. ## Helpers
  13. # Displays a label, field, and error message (if available) for the specified object/method pair.
  14. #
  15. # *Valid Options*
  16. # :label => "The label to use" # Defaults to humanized method name
  17. # :type => :text_field # A method which accepts object_name, method, and field_options. See
  18. # # ActionView::Helpers::FormHelper, ActionView::Helpers::FormOptionsHelper etc.
  19. # :float => false # If true, the field will be wrapped in a div with the floating_input class.
  20. #
  21. # The field_options hash will be passed to the FormHelper method intact.
  22. #
  23. # If a block is provided to field_proc it will be used to build the field.
  24. def field_for(object_name, method, options = {}, field_options = {}, &field_proc)
  25. options[:label] ||= method.to_s.titlecase
  26. options[:type] ||= :text_field
  27. options[:float] ||= false
  28.  
  29. label = content_tag("label", options[:label], :for => "#{object_name}_#{method}")
  30.  
  31. obj = get_object_from_string(object_name)
  32. unless block_given?
  33. # Call the requested method
  34. field = self.send(options[:type], obj, method, field_options)
  35. else
  36. field = field_proc.call(obj)
  37. end
  38.  
  39. errors = error_message_on(object_name, method, options[:label] + " ")
  40.  
  41. if options[:type] == :check_box
  42. fieldset = content_tag("div", field + " " + label + errors, :class => "checkbox_group")
  43. else
  44. fieldset = label + field + errors
  45. end
  46.  
  47. fieldset = content_tag("div", fieldset, :class => "floating_input") if options[:float]
  48.  
  49. return fieldset
  50. end
  51.  
  52. def get_object_from_string(object_name)
  53. if object_name.is_a?(String) || object_name.is_a?(Symbol)
  54. obj = instance_variable_get("@#{object_name}")
  55.  
  56. raise ArgumentError.new("Invalid object name #{object_name} provided to get_object_from_string") if obj.nil?
  57. else
  58. obj = object_name
  59. end
  60.  
  61. return obj
  62. end
Add Comment
Please, Sign In to add comment