I’m creating a rails gem that adds functionality to Rails’ fields_for method, and I’d like it to be callable from any form builder. To keep things concise, inheritable (from form_for, nested_fields_for, etc), and backwards-compatible, I’m beginning to think overriding the fields_for method is the best way to go about it.
I’ve not done this before though, and I can envision some ugly problems. Specifically:
-
I need to call the original fields_for method (via alias_method) in the new one. If Rails changes how that method works in the future, I’m guessing my gem will break all fields_for functionality(?)
-
If another gem overrides fields_for, I suspect either my or the other gems’ fields_for method will be ignored(?)
-
In general, the idea of overwriting an existing rails method just seems pretty shifty.
I’m sure this is something other developers face, and I’m just wondering – what’s the standard approach to overwriting rails methods? Is it a big taboo amongst better developers? Is there another approach to this sort of issue? Should I just sod my attempt for a concise, elegant solution and do it up with a different method name after all?
Any suggestions appreciated.
Rather than overriding your methods, I would take a page from simple_form and formtastic. Both of which effectively change the form_for method, but they create a new method on top.
This way you can delate out to form_for for everything you don’t respond to, and stay insulated from method signature changes.