Refactoring Rails challenge: initializers
Today, I'd like to challenge you to refactor a Ruby file in Rails itself.
It's rails/railties/lib/rails/initializable.rb.
Look daunting? Read on for why I think you should try.
How do we grow our Ruby skills?
To teach yourself new skills, I often find it helps to look at existing pieces of code and try to see if you can improve it.
Rails' source code is a great place to pick out methods or files to therapeutically refactor because there's so much Ruby. At worst, you'll learn more about the innards of the framework. But at best, you'll grow your sensibilities and skills in working with effectively with legacy code.
These samples can also be a great place to try out new Ruby features or syntax, and see whether you like them.
Do you see some code that looks odd to you? Keep peeking at that and follow your curiosity.
Anything stand out as overly complex? Maybe it is just so!
Better code can often be subjective, so feel free to explore and get comfortable with your own answer. We're all human and somebody wrote what you're looking at, and are trying to improve, to the best of their ability at the time. Now you get to do the same.
What's the point of therapeutic refactoring?
Look, I'm all in favor of working code, but when I'm not on the clock I prefer %95 accuracy. That means I'll do my best to check that what I'm rewriting works, but I may not bother getting the tests to setup and run.
I put more emphasis on the therapeutic part than the exact refactoring part. Your mileage may vary.
Also? It's fun to make a mess for something that's throwaway. You'll quickly find out why certain best practices are in place and why people recommend.
I recommend making more mistakes — those scrapes can always be reverted in git anyway.
Also if you "only" make it 5% better, that's great!
This is kind of a long-winded way of saying that therapeutic refactoring to me is, whatever you make of it and feel good about.
Until next week: try your version and send it to me
I looked at the initializable.rb file a few years ago, and I'll share my version next week. Hopefully in a walkthrough.
If you want to try your hand at improving this file, put your version in a gist and send it my way. Reply to this email, or shoot me a DM @kaspth with the link. You have until Saturday August 10th (2024).
The initializable_test.rb test file is here. To run them, you'll need a git clone
or codespaces setup of Rails, then cd railties
, bundle install
etc. and then bin/test test/initializable_test.rb
. It's been a while since I've set any of that up, so I don't quite remember. Bonus XP!
Have fun, see ya!