Reputation: 691
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. I am adding a class into a module with const_set
, but that code isn't ever actually being run. 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. 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. I know I must be missing something really trivial, but I can't figure out what that is.
Here is 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
:
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. 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). When I require 'mygem'
, then MyGem::MyClass
is then defined. 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. Can anyone spot what I'm doing wrong?
Upvotes: 0
Views: 1322
Reputation: 691
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
. 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'
. 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 :).
Upvotes: 1