1

Rails 6.1 has released an improvement for a tag_helper (specifically for the rich_text_area from ActionText), that I would require now, for my Rails 6.0.x app. Basically the improvement is a very small change in just one line of code, so it should be simple to just monkey patch the current rails method and get the improvement now, right?

Specifically I'm trying to monkey patch the following ActionText tag helper method (link to Github rails/rails) with the following code, but the code is not applied. What am I doing wrong?

lib/core_ext/rich_text_area.rb

module ActionView::Helpers
  class Tags::ActionText < Tags::Base

    def render
      options = @options.stringify_keys
      debugger
      add_default_name_and_id(options)
      options["input"] ||= dom_id(object, [options["id"], :trix_input].compact.join("_")) if object
      @template_object.rich_text_area_tag(options.delete("name"), options.fetch("value") { editable_value }, options.except("value"))
    end

  end
end

Added the following to a file in config/initializers

Dir[File.join(Rails.root, 'lib', 'core_ext', '*.rb')].each { |l| require l }
fydelio
  • 932
  • 1
  • 8
  • 22
  • Try putting your code in initializers/action_view/helpers/tags.rb ;) Let me know if that works – Alexis Clarembeau Nov 28 '20 at 14:24
  • @AlexisClarembeau, didn't work. Instead of opening the class, I replaced line 2 with Tags::ActionText.class_eval do (so it would fail if the class didn't exist yet) - what id did. RailsError: uninitialized constant ActionView::Helpers::Tags::ActionText (NameError). That is probably a clue - but not sure on how to proceed from here. – fydelio Nov 28 '20 at 16:47

1 Answers1

2

You can monkey patch in a cleaner way something like this in your lib/core_ext/rich_text_area.rb file:

require 'action_text/tag_helper'

module ActionTextOverride
  def render
    options = @options.stringify_keys
    add_default_name_and_id(options)
    options['input'] ||= dom_id(object, [options['id'], :trix_input].compact.join('_')) if object
    @template_object.rich_text_area_tag(options.delete('name'), options.fetch('value') { editable_value }, options.except('value'))
  end
end

class ActionView::Helpers::Tags::ActionText
  prepend ActionTextOverride

end

Note: The error you were getting RailsError: uninitialized constant ActionView::Helpers::Tags::ActionText (NameError) when trying to use class_eval can be solved by using require 'action_text/tag_helper'

Source: When monkey patching an instance method, can you call the overridden method from the new implementation?

Deepesh
  • 6,138
  • 1
  • 24
  • 41