[英]Creating a Gem that adds a rails form helper
I'm creating a gem to add a new helper method for rails forms. 我正在创建一个gem,以为rails表单添加新的辅助方法。 My gem is a single file
我的宝石是一个文件
lib/rails_json_field.rb
that looks like this: 看起来像这样:
require 'action_view/helpers'
require 'action_view/context'
require 'securerandom'
module ActionView
module Helpers
class FormBuilder
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::JavaScriptHelper
include ActionView::Context
def json_field_tag(method, options = {})
#function code here
end
end
end
end
ActiveSupport.on_load(:action_view) do
include ActionView::Helpers::FormBuilder
end
However when I use the method like so: 但是,当我使用这样的方法时:
= f.json_field_tag(:some_method)
I receive the following error: 我收到以下错误:
ActionView::Template::Error (undefined method `json_field_tag' for #<ActionView::Helpers::FormBuilder:0x007ffa84ab52a8>)
How do I make the method available on ActionView::Helpers::FormBuilder
? 如何使该方法在
ActionView::Helpers::FormBuilder
上可用?
You have defined the following class: 您已经定义了以下类:
RailsJsonField::ActionView::Helpers::FormBuilder
You meant to monkeypatch the following class: 您本来打算补习以下课程:
ActionView::Helpers::FormBuilder
That's why the error message is telling you the method is undefined; 这就是为什么错误消息告诉您方法未定义的原因; you have defined it within a class within your custom module, not within the specified class:
您已在自定义模块的某个类中定义了它,而不是在指定的类中定义了它:
undefined method `json_field_tag' for #<ActionView::Helpers::FormBuilder
It's only defined in RailsJsonField::ActionView::Helpers::FormBuilder
, so you get the above error. 它仅在
RailsJsonField::ActionView::Helpers::FormBuilder
,因此您会遇到上述错误。
If you want to properly monkeypatch the original code then you should look at the original code to ensure your code looks like their code : 如果您想正确地修补原始代码,则应查看原始代码以确保您的代码看起来像它们的代码 :
module ActionView
module Helpers
class FormBuilder
def json_field_tag(method, options = {})
# function code here
end
end
end
end
It would be better to define this as an initializer in your Rails app, eg, in config/initializers/json_field_tag.rb
. 最好在Rails应用程序中将其定义为初始化程序,例如在
config/initializers/json_field_tag.rb
。 Once you have the code working as a simple patch, then you can focus on developing it into a standalone gem that enhances ActionView
. 将代码用作简单补丁后,您就可以集中精力将其开发为增强
ActionView
的独立gem。
After searching, I found a different gem that adds a FormBuilder method. 搜索之后,我发现了另一个添加FormBuilder方法的gem。 I used their repo as a guide to structure my own.
我用他们的仓库作为构建自己的指南。 For others with this questions, you can view my repo and their repo here respectively:
对于其他有疑问的人,您可以在这里分别查看我的仓库和他们的仓库:
https://github.com/dyeje/rails_json_field https://github.com/dyeje/rails_json_field
https://github.com/Brantron/john_hancock https://github.com/Brantron/john_hancock
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.