简体   繁体   中英

How do I get the root directory of a Rails app in a Gem

Is it possible to know the Rails file system root of an application in the code of a gem included in an app?

This is a sample of the gem source:

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

ActionController::Base.send :include, MyGem

Thank's and sorry for my poor english

The solution that I found to fix a similar problem to this is to include my module using the 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 included after the ActionController is loaded and you will be able to use Rails.root

Let me know if this works for you.

Of course:

Rails.root

Just because you're writing a gem doesn't mean you can't access the global namespace. The only concern would be if your Gem uses that access before the Rails module is set up during initialization. If you find that's the problem, post the code you're using, where it is, and we'll be glad to help debug the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM