Watching this video by Yehuda, and he gave this snippet about how Ruby helps you build better abstractions.
class FOWA
def self.is_fun
def fun?
true
end
end
is_fun
end
He was talking about, in ruby, how if you are repeating code in your class over and over again, you can abstract it out without having to think about things in terms of methods etc. And he said this was using a metaprogramming technique.
Can someone explain what this is?
It is a class method on FOWA (so its like a static method, you don’t need an instance to call it), and this class method is really just wrapping another method that returns true.
And this is_fun class method is now being executed or what? not sure what the last line “is_fun” is doing?
The
is_funcall at the end of the class calls the static method. The static method then defines thefun?method inside of the FOWA class. Then, you can do this:If you take out the
is_funcall at the end of the class, thefun?method doesn’t get defined.He mentioned that you wouldn’t use it in this way, but the point is how easy it is to dynamically add a method to a class. You might use it like this if you wanted the method to be available in subclasses and you wouldn’t call
is_funin FOWA, but you might in a subclass. It gets a little more interesting if you have a parameter foris_funand the definition offun?changes depending on that parameter.This also leads right into
modulesbecause you can define amodulewith the sameis_funmethod and then just have your classextendthemoduleand the methods in themoduleare available in the class. You would use this technique if you want your method to be available to more than just subclasses of FOWA.