添加表单帮助程序方法

Arc*_*ath 5 plugins ruby-on-rails

我在jQuery中做了一个很好的编辑器,我想把它添加为一个表单助手方法.

我将如何制作新的表单助手方法?

理想情况下,我喜欢能够打电话:

f.nice_editor :field
Run Code Online (Sandbox Code Playgroud)

Lex*_*sey 9

部分问题是:你在哪里放置nice_editor代码?我不认为在您的安装中直接编辑类ActionView :: Helpers :: FormBuilder是个好主意.相反,将您的代码放在app/helpers中的一个文件中.有几种方法可以向FormBuilder添加扩展方法.

例如,假设您有一个帮助文件items_helper.rb:

module ItemsHelper
    # this is one way to define new instance methods
    ActionView::Helpers::FormBuilder.class_eval do
        def nice_editor(conf,*opts)
            ...
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

另外,请参阅此讨论,其中显示了如何使用self.included()来扩展FormBuilder.


Aug*_*aas 6

产生的对象form_for是一个实例ActionView::Helpers::FormBuilder.所以你要做的就是在那里添加实例方法.

class ActionView::Helpers::FormBuilder
  def custom_field(...)
    ...
  end
end
Run Code Online (Sandbox Code Playgroud)