开发者

Rails automatically call application helper methods any time form_for is called

In my application, any time there is a form, I call two helper methods to inject some javascript into the head of the web page. One method injects code to focus on the first input of the form and the second method hooks up some call backs that I use with the client_side_validation gem.

I will be calling these two methods on any page that has a form_for in the view. Is there a 开发者_开发技巧way to automatically invoke these methods any time form_for is called as opposed to adding the calls to my template files?

Using Rails 3.1.


You should wrap form_for with your own method that calls your helpers. Fortunately Rails provides an easy way of doing this in the form of alias_method_chain.

module ActionView::Helpers::FormHelper
  def form_for_with_my_helpers (*args)
    my_helpers
    form_for_without_my_helpers (*args)
  end
  alias_method_chain :form_for :my_helpers
end

You can now call form_for_without_my_helpers with the normal form_for arguments if you don't want a form to use your helpers.

This can go somewhere that's in the load path. Or you can require the file holding this code.


You shouldn't be using Rails helper methods for these. You should be using jQuery. Add this to your application.js file:

$(document).ready(function() {
  $('form>input:first-child').focus();
}

That's an example, use a similar method for the callbacks you're talking about.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜