How to get the root directory of a Rails application in Gem

Is it possible to find out the root of the Rails file system of an application in the gem code included in the application?

This is a sample of a gemstone source:

module MyGem
  def self.included(base)
    puts Rails.root # return nil
  end
end

ActionController::Base.send :include, MyGem

Thank you and sorry for my poor English

+5
source share
2 answers

The solution I found to fix a similar problem is to enable my module using railtie initializers.

So in your /lib/mygem/railtie.rb

module MyGem
  class Railtie < Rails::Railtie
    initializer "Include your code in the controller" do
      ActiveSupport.on_load(:action_controller) do
        include MyGem
      end
    end
end

With this code, your module will be enabled after loading the ActionController, and you can use Rails.root

Let me know if this works for you.

+7
source

Of course:

Rails.root

, , , . , Gem , Rails . , , , , , .

+2

All Articles