How to use classes from plugin's "lib" folder?

673 Views Asked by At

I created plugin in Rails 4.2.3 which also has some classes in its "lib" folder:

lib/xxx/some_class.rb

Next, I created application and included that plugin as gem:

gem 'myplugin', path: "/path/to/plugin/myplugin"

Unfortunately SomeClass is not visible from within application.

I'm wondering what is best method to include that and other classes from plugin's "lib" folder. I know that in application's application.rb file I could add:

config.autoload_paths += Dir["/path/to/plugin/myplugin/lib/**/"]

But I don't like that I have to explicitly specify entire path to the "lib" folder. Is there better way to do it?

2

There are 2 best solutions below

2
Francesco Belladonna On BEST ANSWER

In this case, it should be enough:

require 'xxx/some_class'

In the file using your SomeClass. To give you an insight on what bundler will do for you (and Rails), they will require for you the file in lib/yourplugin.rb, if you require 'xxx/some_class' in that file, it will be "autoloaded" in rails, otherwise you just need to require it in the files you need.

0
awendt On

This should work out-of-the-box. Have a look at ActiveRecord's lib/ tree, there's a subdirectory, too.

I guess you're not specifying the module that Rails' auto-loading sets up for subdirectories.

Example: Even though ActiveRecord comes with a class Base, that class won't be visible without the namespace. That's why you use ActiveRecord::Base in your models.

If your plugin puts the classes under lib/my_plugin/some_class.rb, Rails will find the class when you specify MyPlugin::SomeClass but not just SomeClass.