How to extend the "unloadable" Rails plugin?

I am trying to write a plugin that will extend InheritedResources .

In particular, I want to rewrite some default helpers.

And I want it to "just work" after installation, without any changes to the application code.

Functionality is provided in the module, which must be included in the right place . The question is where? :)

The first attempt was to do this in my init.rb plugin:

InheritedResources::Base.send :include, MyModule

It works in production, but it is difficult to develop, since InheritedResource :: Base is declared as unloadable, and therefore its code is reloaded for each request. So my module exists for the first request, and then it went away.

InheritedResource :: Base is again pulled in by any controller that uses it:

Class SomeController < InheritedResource::Base

But not a single code “pulls” my extension module, since it is not mentioned anywhere except init.rb, which is not reloaded on every request

So right now, I’m just manually plugging the module into every controller that needs it, which sucks. I can't even include it once in the ApplicationController, because InheritedResources inherits it, and so it will override any changes.

Update

I am not looking for advice on how to "patch the monkey." The extension works in production just fine. my problem is how to catch the moment immediately after InheritedResources is loaded to insert the extension into it :)

Update2

another attempt at clarification:

sequence of events

  • a) . inherited_resources .
  • b)
  • c) rails "" , , inherited_resources
  • d)
  • e) ,
  • f) rails , application_controller
  • g) rails application_contrller ( , )
  • g) , patch inherited_resources. plugin init.rb .

g h

+3
2

Rails:: Configuration, config , , , .

config.to_prepare do
   # do something here
end

, , config init.rb. . init.rb.

require 'dispatcher'
::Dispatcher.to_prepare do
    puts "hi there from a plugin"
end

: , . , config .

+4

, , "MonkeyPatch" - "".

Rails, , - - , ( ).

, " ": lib/. lib rails lib , .

, , , lib/generators/rails/templates/controller.rb , , , lib/(lib/generators/rails/templates/controller. ')

( ) . /. :

module foo
  module bar
    def f1
    ...
    end
    def f2
    ...
    end
  end
  def f3
  ...
  end
end

f1, foo-bar.

module foo
  module bar
    def f1
    ... # your code here
    end
  end
end

, , , . lib/lib , initializers/ require . gem/plugin, init.rb . "require" .

unloadable; , - -, ... ? ( , )

-1

Source: https://habr.com/ru/post/1735818/


All Articles