Namek Dev
a developer's log
NamekDev

Why is Ruby so entertaining? Mixins.

August 16, 2012

Ruby

Ruby [0] is a simple, yet powerful language, thanks to which developers are enabled to create or programmatically sketch many things in a fast manner. It’s good for prototyping GUI (Shoes [1]), web development (Rails [2], Merb [3]) or even for network administrator’s scripting (for massive or scheduled actions).

The question today is - why are there so many people interested in that language? I think that one of strong features are mixins.

Mixins

Most important thing about Ruby is that it’s easy to extend any API to your own goods. Meet feature called mixin. A mixin is a piece of code that can be injected into the class dynamically. To be more clever Ruby has class and modules, thus mixin is a class that is mixed with a module [4]. It differs from class inheritance in that way that our extended class doesn’t really have to inherit from our mixin (but it’s possible anyway, read the following). Let’s look at the live example:

module Animal
  def eat
    //do something
  end
end

module Predator
  def bite
    //omg
  end
end

class Dog
  def bark
    //do something
  end

  extend Animal
  include Predator
end

Look at the Dog class. We defined it in one piece with Animal and Predator modules but it could be done in some other file. What I’ve done here was dynamic inheritance from the Animal module and include of Predator module. To shorten explanations, it will work in that way:

class Dog < Animal
  def bark
  end

  def eat
  end

  def bite
  end
end

Dynamic extend of core classes

Here’s a nice short explanation. The Code [5]:

class String
  def capitalize_each
    self.split(" ").each{|word| word.capitalize!}.join(" ")
  end
  def capitalize_each!
    replace capitalize_each
  end
end

puts "hello WORLD!".capitalize_each #=> "Hello World!"

Class String already existed in Ruby so why writing such a thing? That’s why Ruby is so interesting - it’s objective and it enables us to extend core classes. That makes us possible to do with strings whatever we’d like to and it’s cool.

There’s more

Ruby is pretty dynamic, right? There are few more interesting features:

  • modules can be informed about that they are being mixed with class (through self.extended or self.included event methods) [4]
  • modules can act as namespaces [6]
  • class can mix in more than a one module [6]

References

ruby
comments powered by Disqus