Okay guys, I've been beating my head against the wall with this one all day and was hoping I might garner some enlightenment from the gathered geniuses. I am including some pared down code to demonstrate my issue.
Basically, I want my form builder to automatically add an :onchange handler to a specific form field (for my example, I am using
My problem is that unless I pass in at least one hash value to the field helper, the option doesn't get added. i.e.:
[b]These work (the onclick will get added):[/b]
[code]<%= f.text_field :title, :class => 'sexy' %>[/code] [code]<%= f.text_field :title, :label => 'Topic' %>[/code] [code]<%= f.text_field :title, :class => 'sexy', :label => 'Topic' %>[/ code]
[b]This does not (no onclick, very sad):[/b] [code]<%= f.text_field :title %>[/code]
I have appended question marks to the blocks in question below.
[code] class ExampleFormBuilder < ActionView::Helpers::FormBuilder
def self.create_tagged_field(method_name) define_method(method_name) do |attr, *args| options = args.extract_options!
# ?? This doesn't work unless the field helper in the view is passing in a hash of options. ?? #options.merge!(:onclick => "alert('foo');") # ?? Direct assignment doesn't work either ?? #options[:onclick] = "alert('foo');"
label_text = "#{options[:label] || attr.to_s.humanize}:" label = @template.content_tag('label', label_text, :for => "# {@object_name}_#{attr}")
# remove my custom hash key so it doesn't pollute the output options.delete_if {|key, value| key == :label}
# ?? I don't need to do this, but why ?? #args = (args << options) unless options.blank?
@template.content_tag('p', label + '<br />' + super) end end
field_helpers.each do |name| create_tagged_field(name) end
end [/code]
Even if I am not passing in a hash, the extract_options! command should create a hash object from the args, so I don't know what I'm missing here.
My second part to this question is around the splat operator, *args, and options. Let's say I pass the field helper the option :class => 'sexy'. Now, since I am extracting the options hash from the args, I assumed I needed to add them back in before calling super. But spookily enough, I don't. Do the options extracted from *args maintain a reference, or am I missing something completely obvious.
Any and all help would be massively appreciated. I will even send you
a facebook gift.