简体   繁体   English

如何在Gem中获取Rails应用程序的根目录

[英]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? 是否可以在应用程序中包含的gem代码中了解应用程序的Rails文件系统根目录?

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. 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。

So, in your /lib/mygem/railtie.rb 所以,在你的/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 使用此代码,您的模块将在加载ActionController后包含在内,您将能够使用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. 仅仅因为您正在编写gem并不意味着您无法访问全局命名空间。 The only concern would be if your Gem uses that access before the Rails module is set up during initialization. 唯一需要关注的是,如果您的Gem在初始化期间设置Rails模块之前使用了该访问权限。 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. 如果您发现问题所在,请发布您正在使用的代码,它在哪里,我们很乐意帮助您调试问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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