Plugin Patterns eager loading

1 view
Skip to first unread message

Leandro Pedroni

unread,
Feb 16, 2009, 2:59:06 PM2/16/09
to PeepCode
Hi, I was playing with the recipe on the plugin pattern pdf on page
21:

module MyModule

def self.included(base)
base.extend ClassMethods
base.include InstanceMethods
end

module ClassMethods...
module InstanceMethods...

end

But if I send the include to a class it complains since I'm calling -
include- on what is passed in the -self.included- hook
Changing that bit into:

def self.included (base)
base.extend ClassMethods
base.class_eval do
include InstanceMethods
end
end

produces the desired effect. Is the other one incorrect? Was the
module intended to included from somewhere in particular?

thanks,
Leandro

Andrew Stewart

unread,
Feb 19, 2009, 7:56:03 AM2/19/09
to peep...@googlegroups.com
Hi Leandro,

Please could you send me the code you're using to include your module
in a class? I'll have a better idea then what the problem might be.

Normally I would do something like this:

class MyClass
include MyModule
end

Or even:

MyClass.send :include, MyModule

Have you had a chance to read the section on Modules, pages 7-10? If
not, you might find the answer there.

Regards,
Andy

-------
Andrew Stewart
AirBlade Software Ltd
http://airbladesoftware.com

Leandro Pedroni

unread,
Apr 3, 2009, 6:25:09 PM4/3/09
to PeepCode
They both yield the same result:
=> NoMethodError: private method ‘include’ called for MyClass:Class

This is the full code (inspired by page 21) that throws me the error:

module MyModule
def self.included(base)
base.extend ClassMethods
base.include InstanceMethods
end

module ClassMethods
def classy
puts "Stay classy"
end
end

module InstanceMethods
def instance_m
puts "I'm an instance method"
end
end
end

class MyClass
include MyModule
end

MyClass.classy

Leandro

Andrew Stewart

unread,
Apr 4, 2009, 11:56:56 AM4/4/09
to peep...@googlegroups.com

On 3 Apr 2009, at 23:25, Leandro Pedroni wrote:
> They both yield the same result:
> => NoMethodError: private method ‘include’ called for MyClass:Class
>
> This is the full code (inspired by page 21) that throws me the error:
>
> module MyModule
> def self.included(base)
> base.extend ClassMethods
> base.include InstanceMethods
> end
<-- ... -->
> end


I think you have found a mistake on page 21, for which I apologise!
The problem is that +include+ is a private method of class Module; and
private methods cannot be called with receivers. The only way to call
+include+ on something other than +self+ is to bypass the private
restriction by sending the :include message like this:

base.send :include, InstanceMethods

You can see this technique on p.23 where the hook code in init.rb is
described:

ActiveRecord::Base.send :include, YourName::PluginName

Regards,
Andy Stewart

-------

Reply all
Reply to author
Forward
0 new messages