As Ruby programmers, I think we enjoy the ease and power of being able to extend any core Ruby class. As our ruby-fu grows, we pick up some tricks to have Hash’s and Struct’s to do our bidding, monkeypatched or not. So naturally we start collecting extensions. Sometimes they’re cool enough to blog about, sometimes you find out a week later that Ruby’s stdlib or activesupport already does it better. Eventually collecting enough of them, you decide to gem or github them because you want to share what you’ve learned. You want others to use it. Heck, maybe even get feedback on them. So when releasing them, why do we force monkeypatching?
class Object def awesome_instance_method end def self.awesomer_class_method end end
Why do this when it’s easy to do the same without monkeypatching?
module Awesome module Object def awesome_instance_method end module ClassMethods def awesomer_class_method end end end end # In a separate file that you will require: Object.send :include, Awesome::Object Object.send :extend, Awesome::Object::ClassMethods
No, I’m not trying to reignite monkeypatch debates. Rather, just hoping that as a community, we can release monkeypatch-agnostic extensions and let the programmer decide when to monkeypatch.
So why do I think everybody monkeypatches their extensions? Take a look at some of the Ruby extension libraries out there:
And there’s still more on github …
Of the above extensions, ActiveSupport is the ONLY one that doesn’t force monkeypatching:
gem 'activesupport' require 'active_support/core_ext/array/access' class My; class Array < ::Array; end; end My::Array.send :include, ActiveSupport::CoreExtensions::Array::Access
So can we share our extensions without monkeypatching?