Ruby Boolean
03 May 2015Week one of my Year of Commits initiative is complete, 51 more to go. I did not plan on telling people about this until a few weeks into the task (in case history repeated itself and I gave up 20% in). But that didn’t happen; people found out about it almost immediately, demonstrating yet again just how easy it is to find anything on the Internet. Thanks, Obama.
So what happened in the first week? Did I change the world of open source forever? Did I contribute a monumental change to one of the most well renown ruby libraries out there? Nope, I made a gem that at its core is 3 lines long. I made a boolean gem.
I can see that most people would wonder: “Why?”, “Why did he make this useless thing? Doesn’t he know that ruby does not have the boolean type by design?”. The answer is simple. I found myself over and over again typing some kind of nonsense like this:
# For some reason we need to know if this value
# is a boolean or not
#
# @boolean?
# param: value - what we want to know is a boolean or not
# return: true/false
def boolean?(value)
value.is_a?(TrueClass) || value.is_a?(FalseClass)
end
This, however, could also be questioned. “Who cares if something is a boolean or not? This is ruby, duck-type that shiz”. Sure, that makes sense, I can do that. But do I want to do that? No. Why not? Because sometimes knowing the type of something can be important. You might not always have a background process like ActiveRecord’s type coercion to clean up your types for you. Or maybe you actually want something to be a boolean, not 't'
or 'f'
.
This gem is not alone. Other gems that do similar and much more functionality exist as well (i.e. bool and boolean)
With the ruby-boolean gem, the same kind of code can be re-written:
# Super important business logic method
def some_method_where_booleans_matter
if thing.is_a?(Boolean)
# Do boolean related stuff
else
# Throw a fit about it not being a boolean
end
end
Great! Now I only have to check one class instead of two. My life is now perfect, what could possibly make this any better? Nothing.
This project was a fun introduction to the 365 commit-a-thon I am embarking on. Maybe someone will even use it.