开发者

Sample Ruby code, How is this abstracting things out?

Watching this video by Yehuda, and he gave this snippet about how Ruby helps you build better ab开发者_C百科stractions.

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?

http://vimeo.com/11679138


The is_fun call at the end of the class calls the static method. The static method then defines the fun? method inside of the FOWA class. Then, you can do this:

f = FOWA.new
f.fun?

If you take out the is_fun call at the end of the class, the fun? 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_fun in FOWA, but you might in a subclass. It gets a little more interesting if you have a parameter for is_fun and the definition of fun? changes depending on that parameter.

This also leads right into modules because you can define a module with the same is_fun method and then just have your class extend the module and the methods in the module are available in the class. You would use this technique if you want your method to be available to more than just subclasses of FOWA.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜