Generic-user-small Bharat Ruparel 29 posts

David,
You keep saying that include is a private method throughout the screencssts (specifically episode 4 towards the end in the class_eval section). May be it is obvious, but I don’t get it. How can include be a private method and be used inside a class or module or even be called from outside? I am not talking about the class_eval {include .. } but include in general. Perhaps an example snippet will explain it?
Regards,
Bharat

 
Dave_8_trans_small Dave Thomas Administrator 70 posts

Bharat:

A private method is Ruby is one that cannot be called with a receiver, and therefore can only be called in the context of the current object. include() is a private method of class Module, and therefore can only be called when self is a Module or subclass thereof.

 
Generic-user-small Bharat Ruparel 29 posts

Thanks for the quick reply. I understand what you are saying in the screen cast now.
I am referring to episode 4 – use 3: it seems to me that this kind of use of include as shown in the code snippet below:
module Hello def say_hello puts "hi from #{self.inspect}" end end [ String, Array, Hash ].each do |cls| cls.class_eval { include Hello } end

“cat”.say_hello
[1,2].say_hello
{ 1 => 2 }.say_hello

is a “bad” idea since it breaks encapsulation? You mention towards the end that Rails uses this but did not say whether it was a good or a bad thing. Can you comment on it?

There is a reason why I am asking this question. I come from a Java background and the Meta Programming is kept to a minimum even though the source code can be quite long. It seems to me that if the only purpose of writing this kind of code is to shorten the total lines of code statistic then it is definitely a bad thing to do. On the other hand, if there is something more concrete to be gained, then it is a good thing. I am asking you if there is a more compelling reason to do this kind of thing in practice besides just being clever?

 
Dave_8_trans_small Dave Thomas Administrator 70 posts

Bharat:

It’s all contextual. When it’s good, it’s good. When it isn’t, it isn’t. Part of the skill of programming is knowing the difference, and that experience comes from trying, making mistakes, and learning.

In general, the motivation is never simply to write shorter code. It’s to write more maintainable code—code that’s easier to work with and change.

4 posts, 2 voices