RE: Modules vs. Classes ... (click to expand) ...
First of all you MUST use a toplevel author or company namespace module.
Since it’s likely that you’ll have multiple plugins, each plugin should have it’s own module namespace wrapper to separate it from other of your plugins.
Since a plugin is a singleton object (there is only ONE instance of it,) it should be a module, which is an instance of class Module
. A class is used to instantiate multiple instances of an object. A plugin scenario is not proper use of a class.
FYI, class Class
is the direct child subclass of class Module
, so they inherit everything modules have anyway, but more important only has different the instantiating functionality added, which is not needed by a singleton plugin / extension object.
The only reason that you see other people’s code of forum examples use class objects as a singleton plugin object, is because they wanted to call other methods in the namespace without namespace qualification. But this is a misuse of classes, and is not necessary.
There are two ways to use a module where methods can call each other without the self.method_name
or MyModule.method_name
qualification.
The older way:
module Author::SomePlugin
class << self
# define all methods here
end
end
The now prefered way actually uses the module itself as a mixin module to extend itself (see Object#extend
) …
module Author::SomePlugin
extend self
# define all methods here
end
I used the new way in the example.
With the old way it would be confusing as to whether to define constants variables etc., within the block of the anonymous singleton class instance or in the outer plugin module. With the new way everything is defined in that one module level.