One Base Class to Rule Them All
Last week, I released base, a universal Base class for Ruby. Inheriting from it gives your class every instance method, class method, and constant from every module and class in the system. In a Rails app, it results in:
>> Base.new.methods.count => 6947
Let's see just how powerful this is. We'll start with a subclass of Base:
class Cantaloupe < Base end
This class has the methods—all of them. Like, for example,
>> p Cantaloupe.new.size => 0
The size of the cantaloupe is zero. Fine. But you might be wondering, where did that
size method come from? There are so many in Ruby. Is it
The answer is: maybe. But the real answer is: this is Ruby! We just call methods and things happen! We don't have to worry about it! Isn't this great?!
You can call any method you want! Like, say,
days from ActiveSupport:
>> Cantaloupe.new.days TypeError: can't convert nil into String from base.rb:78:in `new' from base.rb:78:in `instantiate_regardless_of_argument_count' from base.rb:76:in `each' from base.rb:76:in `instantiate_regardless_of_argument_count' from base.rb:71:in `call_instance_method' from base.rb:47:in `call_method' from base.rb:43:in `each' from base.rb:43:in `call_method' from base.rb:37:in `method_missing' from (irb):3
Wait... why didn't that work? Whatever, it's not important. We're Ruby programmers; we have ways around errors! Like this:
>> Cantaloupe.new.days rescue 5 => 5
See? A cantaloupe has five days. Don't worry about it. It's fine.
You could even ask the
find_by_email. Why worry about which model it will find? You'll find something by email; that's for sure!
In addition to all of this method-calling convenience, Base also leads to superior object oriented design. Remember the Law of Demeter? The one that says "talk to your friends, but not your friends' friends"? With Base, all other classes are your friends! You can call any of those 6,947 methods while complying with the Law of Demeter!
Since I'm sure you're itching to
gem install it, base is available on GitHub. Its README contains more details, examples, and praise from the community. Enjoy!
(Disclaimer: believe it or not, I quite like Ruby. In fact, most of Destroy All Software's screencasts use it. If you're interested in actually building good software—doing the opposite of everything in this post—you might enjoy them.)