How to automatically include gem in the path?

I have foo.gem and there is lib/foo.rb .

When I add gem to the Gemfile, foo.rb is automatically required in my path. But I need to turn it on automatically. The reason for this is because I am creating a console extension, and I want them to be available without me, calling `include Foo '.

I am experimenting with

 SOME_CLASS.send(:include, Foo) 

But not sure which class to use to add it to the path, for example. when I start the console, which automatically turns on. Here are a few mixes that are automatically included in the console, I need me to be there :) Thanks.

 irb(main):006:0> self.class.included_modules => [PP::ObjectMixin, JSON::Ext::Generator::GeneratorMethods::Object, ActiveSupport::Dependencies::Loadable, Kernel] 

PS

I can solve the problem with the initializer, but I do not want to change the project code. I just want to add gem and that it works.

+4
source share
2 answers

You must use the Kernel module, which is included with Object . It is where private methods such as exit , puts and require are defined, so it is a great choice for defining an imperative API.

When you extend Object , people expect to be able to explicitly call your methods on any object, and also understand that your method depends on this state of the object.

Kernel methods are understood differently. Even if they are technically available for all objects, you do not expect people to write things like:

 'some string'.sleep 1000 

It does not make sense. sleep has nothing to do with a string; it in no way depends on it. It should only be called with an implicit receiver, as if the concept of self itself did not exist.

Creating your private methods and extending Kernel instead will help you get this message.


You can do this in foo.rb :

 module Foo # … end Some::Class.send :include, Foo 

When you load or require some file, it runs line by line. You can put arbitrary code anywhere in the file, even inside module and class definitions. You can use this to set up your library correctly so that others do not need it.

+1
source

You tried

 Object.send(:include,Foo) 

or

 self.send(:include,Foo) 

inside the console

+1
source

All Articles