ActiveSupport: Humor, Defaults, Security
Reading the source of Rails gives insight into the minds of the contributors over the years. It lets you know how they like to write code (of course), but it also gives you little glimpses into the personalities of particular people who shaped Rails in big and small ways. As a reader, you walk away from comment reading sessions knowing just a little bit more about the code, and the people behind it.
Reading code is fun
For instance, I learned that DHH thinks like a human:
This is something I really enjoy about the Ruby community: a clever sense of humor and a goal to be nice like Matz. If you’re looking for evidence of ‘nice’, you only need to take a cursory glance at the source comments…very generous in their detail, very helpful.
Hash#fetch for defaults
Moving on, I’ve come across the following pattern a few times…I believe one time was while watching Ruby Tapas episode 12, and the other was probably during a DestroyAllSoftware screencast, but it’s cool enough to highlight every time.
When you could do? (from class/attribute.rb)
Hurray for fetch for defaults! Nice and clean…as long as you don’t look at the double assignment thing there. Ignore those ;)
Meta with Module#class_eval
The next little piece of code showcases the dynamic nature of Ruby as well as some metaprogramming essentials. Here a class is opened up and a new class level attribute is shoved onto it (if it doesn’t already exist) and then a method to access said attribute is defined.
For clarity, Module#class_eval takes optional arguments of filename and line number for showing error messages. I was curious about the
__FILE__, __LINE__ + 1 first time I saw that, so that’s the reason for it.
Parsing XML Safely
Remember back a few months when all those security CVEs where coming out? There were a few exploits related to arbitrary code execution and a denial of service from parsing XML. Well lo and behold, I just found some of the code that addresses those issues in hash/conversions.rb
Here you can see how the security hole was patched up:
- fork the from_xml method into a untrusted and trusted version
- blacklist certain types that could be specified in an XML document
- raise the
DisallowedTypeexception if we encounter one of those while trying to parse
There’s more to it than the code shown here, but nonetheless, you get the gist. Very approachable solution, I like it.
That’s all for now, still a ways to go in ActiveSupport but I think I’m about half way through the core extensions.