Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 381
sailor Avatar asked Jun 29 '12 13:06

sailor


1 Answers

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.

like image 53
GiaNU Avatar answered Sep 28 '22 15:09

GiaNU