简体   繁体   English

Rails Railtie初始化程序无法运行

[英]Rails Railtie initializer does not run

I'm developing a gem for use in a Rails 4 application that include a bit of code to be run as an initializer for the host application. 我正在开发一个供Rails 4应用程序使用的gem,其中包含一些代码,可以作为宿主应用程序的初始化程序运行。 I am adding a class into a module with const_set , but that code isn't ever actually being run. 我正在使用const_set将一个类添加到模块中,但是实际上从未运行过该代码。 Also, when I put the gem in my app's Gemfile and start up either the rails console or server, classes that I expect to be defined from the gem are not. 另外,当我将gem放入应用程序的Gemfile中并启动rails控制台或服务器时,我期望从gem定义的类却没有。 If I do a plain require 'my_gem' from the console, then those classes I expect to be defined are finally defined, and if I run the initialization code manually, no errors are thrown. 如果我从控制台简单地require 'my_gem' ,则最终定义了我希望定义的那些类,如果我手动运行初始化代码,则不会引发任何错误。 I know I must be missing something really trivial, but I can't figure out what that is. 我知道我一定会遗漏一些琐碎的东西,但是我不知道那是什么。

Here is mygem/lib/mygem.rb : 这是mygem/lib/mygem.rb

require "mygem/railtie" if defined?(Rails)
require "mygem/version"

module MyGem
  class MyClass

    def self.my_method(argument1, argument2, argument3)
      argument1 == argument2 + argument3
    end
  end
end

Here is mygem/lib/mygem/railtie.rb : 这是mygem/lib/mygem/railtie.rb

module MyGem
  class Railtie < Rails::Railtie

    initializer "mygem.define_subclass" do
      PreviouslyDefinedAppModule.const_set "MyClass", MyGem::MyClass
    end
  end
end

After putting my gem in my app's Gemfile and start up the console, the MyGem module is defined, but MyGem::MyClass is not defined, however. 将我的gem放入应用程序的Gemfile中并启动控制台后,就定义了MyGem模块,但是MyGem::MyClass Also, as far as I can tell, no initializer code from my gem is ever run (it would fail since the class wasn't defined). 而且,据我所知,从未运行过我的gem的初始化程序代码(由于未定义类,所以它将失败)。 When I require 'mygem' , then MyGem::MyClass is then defined. 当我require 'mygem' ,然后定义MyGem::MyClass I've taken a look at a number of rails plugins and railtie tutorials and they all say to just add the gem to your Gemfile and everything should just work. 我看过许多rails插件和railtie教程,他们都说只是将gem添加到您的Gemfile中,一切都应该正常工作。 Can anyone spot what I'm doing wrong? 谁能发现我在做什么错?

I've figured it out almost immediately after I posted. 发布后,我几乎马上就知道了。 My gem name is my-gem , but the module's file name is my_gem.rb . 我的gem名称是my-gem ,但是模块的文件名为my_gem.rb In my host app's Gemfile I have the line gem my-gem , but to actually load the gem I need to require 'my_gem' . 在我的主机应用程序的Gemfile中,行gem my-gem ,但是要实际加载gem,我需要使用require 'my_gem' So, in order to fix this, I need to replace that line in the host app's Gemfile with gem my-gem, require: "my_gem" (or fix this confusing and haphazard naming scheme :). 因此,为了解决此问题,我需要用gem my-gem, require: "my_gem"替换宿主应用程序的Gemfile中的该行gem my-gem, require: "my_gem" (或解决此令人困惑和随意的命名方案:)。

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

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