|
|
| 28 |
30 |
|
| 89 | 89 | # Helper method to determine whether or not +templated_attribute+ has |
| 90 | 90 | # been called for a given class and method. |
| 91 | 91 | def templated?(class_name, method, options={}) # :nodoc: |
| 92 | | klass = class_name.classify.constantize |
| 92 | klass = class_name_from_options_object_or_class_name(class_name, options) |
| 93 | 93 | klass.respond_to?(:templated_attributes_options) && klass.templated_attributes_options[method.to_sym] |
| 94 | 94 | end |
| 95 | 95 | |
| 96 | 96 | |
| 97 | # Utility method to figure out what class the user wants to use. This |
| 98 | # disambiguation is necessary so we can support both +FormHelper+ formats: |
| 99 | # form_for(@user) do |f| |
| 100 | # f.text_field :website |
| 101 | # text_field :user, :website |
| 102 | # end |
| 103 | def class_name_from_options_object_or_class_name(class_name, options={}) |
| 104 | if options.has_key?(:object) |
| 105 | options[:object].class |
| 106 | else |
| 107 | klass = class_name.to_s.classify.constantize |
| 108 | end |
| 109 | end |
| 110 | |
| 111 | |
| 97 | 112 | # Behind the scenes, figure out the starting value for the field, then |
| 98 | 113 | # render the field normally with that value (if applicable) and append a |
| 99 | 114 | # touch of Javascript to add behavior. |
| 100 | 115 | def field_with_templating(field_helper, class_name, method, options = {}) # :nodoc: |
| 101 | 116 | options = { :templated_javascript => true }.merge(options) |
| 102 | | template_options = class_name.classify.constantize.templated_attributes_options[method.to_sym] |
| 117 | klass = class_name_from_options_object_or_class_name(class_name, options) |
| 118 | instance = options[:object] || self.instance_variable_get("@#{class_name}") |
| 119 | template_options = klass.templated_attributes_options[method.to_sym] |
| 103 | 120 | |
| 104 | 121 | # If calling method on object returns nil, use template value instead |
| 105 | | field_value = options[:object].__send__(method.to_sym) |
| 122 | field_value = instance.__send__(method.to_sym) |
| 106 | 123 | if field_value.nil? || field_value.strip.empty? |
| 107 | 124 | field_value = template_options[:value] |
| 108 | 125 | end |
| --- | --- | |
| 118 | 135 | |
| 119 | 136 | # output using the original method with our modified form field value, |
| 120 | 137 | # plus the javascript |
| 121 | | send("#{field_helper}_without_templating".to_sym, class_name, method, options.merge({:value => field_value})) + javascript_string |
| 138 | send("#{field_helper}_without_templating".to_sym, klass.to_s.downcase, method, options.merge({:value => field_value})) + javascript_string |
| 122 | 139 | end |
| 123 | 140 | |
| 124 | 141 | |