3 June 2012

A Gem hack in Rails 3 project

I have a little project, one piece of the main function requires some help from a gem named 'HelloWorld'. However, this gem doesn't have the exact support I need. Before the owner of the gem accept my github pull request, I need do some hack to extend two of the the gem's classes 'Hello' and 'HelloWorld'.

I put the class "Hello" in a file named 'hello.rb', placed the file in the 'lib',
and 'autoload' the 'lib' directory by putting in the following line in the 'Application.rb' file:
config.autoload_paths += %W(#{config.root}/lib)
It worked like a charm! I can invoke the class method of my "Hello" class in Rails Console! Hooary!

Then I changed the class to "HelloWorld", and I renamed my file to 'hello_world.rb'.

Theoretically, it should just work. But it didn't!

After pulling off a few hair from my almost hairless head, I found an interesting article by Bill Harding, and the suggested solution works for me is to force load the new file through initializers.

I created a new file 'extensions.rb' in 'config/initializers',
then put the following line into 'extensions.rb':
require File.join(Rails.root, "lib", "hello_world")
It worked! Well, it's not the way I really wanted it, but I'm happy it worked for me for now.

The 'Autoload' configuration in the 'Application.rb' file is not necessary any more in this case.

Hope it helps.

No comments:

Post a Comment