Ruby on Rails Wednesday, February 29, 2012

I have interesting situation.

a.rb #file
class A
include M
end

b.rb #file
module M
include X
extend Y
end
module X
def instance_method
end
end
module Y
def class_method
end
end

A.class_method => undefined method class_method

Thats strange because what I expect to happen is module M extends Y so
those class methods of Y are copied into A, and hence the A object can
access those class methods.

But thats not what happened. Ruby couldnt find the class methods. Yet
when I change to this it worked:

a.rb #file
class A
include M
end

module M

def self.included(base)
base.send :include, X
base.send :extend, Y
end

module X
def instance_method
end
end

module Y
def class_method
end
end
end

A.class_method => nil

So this works, and the only difference is that X and Y modules are
declared in M. Also I use the included hook which gets called when M
is included in class A, and then passes A into argument list. Then we
dynamically send methods (since include is a private method of A) of
A, particuarly the inclue and extend methods passing our modules as
arguments. And now it works.

But why didnt the first example work?

thanks for response

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment