Turning code into data with Ruby
As an application matures, storing parts of the application code as data empowers the developer. You can alter application behavior with the change of a configuration file rather than digging deep into the application code.
I'll demonstrate this with a common pattern I've noticed, and hopefully you could apply the same principles to parts of your application.
Suppose we need to check to see between which two numbers a given value falls between. Here's an obvious way to do it:
This works but is painful to alter. What if we want to add another range? Five ranges? 20 ranges? This pattern is full of boilerplate.
Here's a much more manageable method:
Now the values for comparison are separated from the code that actually runs the comparison. Want to change any of the range values? Just alter the hash. But here's the best part: combine this with ActiveRecord serialization:
Quick tip about serialization: Ruby ranges do not get properly serialized. That's why I convert them to arrays inside the hash.
11 September 2010