Skip to content
Joan Wolkerstorfer edited this page Jun 19, 2015 · 3 revisions

(copy/paste from Sven’s blog post)

In Ruby what is the most obvious, elegant and maintainable pattern to extend an existing class’ or object’s functionality? No, the answer to that is definitely not in using alias_method_chain. It’s simply including a module to that class. You probably knew that already ;)

We’ve done this with the I18n Simple backend before but one needs to extend the Simple backend first in order to then inject additional modules to the inheritance chain so that these modules’ methods would be able to call super and find the original implementation.

To make this a bit easier I’ve moved the original Simple backend implementation to a new Base backend class and simply extend the (otherwise empty) Simple backend class from it (see here and here). This way you now do not need to extend the Simple backend class yourself but you can directly include your modules into it:

module I18n::Backend::Transformers
  def translate(*args)
    transform(super)
  end  
  def transform(entry)
    # your Transformers logic
  end
end
I18n::Backend::Simple.send(:include, I18n::Backend::Transformers)

I have no clue what your Transformers module could do exactly but that’s the point about extensible libraries, isn’t it? In any case this is simply the pattern that the new, experimental Pluralizations, Fallbacks, Gettext and Cache modules use that I wanted to talk about :)

Clone this wiki locally