dyeje
dyeje

Reputation: 305

Creating a Gem that adds a rails form helper

I'm creating a gem to add a new helper method for rails forms. 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 ?

Upvotes: 0

Views: 375

Answers (2)

dyeje
dyeje

Reputation: 305

After searching, I found a different gem that adds a FormBuilder method. 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/Brantron/john_hancock

Upvotes: 1

anothermh
anothermh

Reputation: 10526

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.

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, e.g., in 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.

Upvotes: 1

Related Questions