Don't change constants in Ruby
I am reviewing a lot of code now, kind of projects that have million plus lines of Ruby code that been (un)maintained for 13 years or so. That’s lot of code and lot of years. Still the project goes strong. I once encountered a thing that crashed our server.
Take this one
SOME_HASH = {}
Now for some reason, this hash constant changes, don’t ask me why, this changes, so the code is like this
SOME_HASH = {}
SOME_HASH[:some_key] = :some_value
Usually in the above code, ruby just warns and lets you a free run. I am kind of against that, but that’s how Ruby works. But now when I run rubocop auto correct against it, the above code get’s transformed to something like below
SOME_HASH = {}.freeze
SOME_HASH[:some_key] = :some_value
So SOME_HASH
is frozen, and it cannot be changed. Rubocop is right, constant should not change, that’s why its a constant! Common!! That’s why rubocop froze it. So when it encounters this line SOME_HASH[:some_key] = :some_value
, what was set not to change, now changes.
So Ruby throws an error and stops code execution. The basic thing is CONSTANT IS CONSTANT and don’t ever change it.