Freezing is a way to stop classes from being changed in ruby, it’s a way to be a bit of a tyrant with your code.
A preferable way to manage other contributors is to use git and merge changes that other coders have committed, and if the code is below par, just ask the nicely for the functionality to be extended via modules for example or just reject those changes.
Here’s how you add method to a class using monkey patching.
f = Freeza.new
class Freeza # twice
I have now decided that I don’t want anything added to this class.
Now I have changed my mind, or another coder wants to add functionality.
Notice how I have wrapped the code in a begin and rescue error catch.
puts "is it me you're looking for"
rescue RuntimeError # this is what we'll get instead
puts "Get back to where you once belonged"
Now that didn’t work
There is no way to unfreeze the class so we need to find a way to unfreeze somehow.
You can inherit from a frozen class and that will not be frozen.
So let’s try that.
puts "hello hello"
f = Defrosted.new
Thats all good, but you might want to convert a variable based on the first class and keep the the values from the old class so this is not very flexible, as you are just replacing a variable.
Freezing isn’t nice
Just don’t freeze, but also keep monkey patching to minimum as it’s one of the most powerful tools in ruby. But it can leave a mess of methods spread across multiple files without form.
Once certain monkey patches become popular then change them to the better way of doing it which is using modules.
You can use modules if you plan to have a variable which has the base functionality of a class, yet with a bit more functionality added.
Here’s how this is done.
# i want the variable f to make cowbell noises
Now that overcomes the potential freezes of objects by extending the functionality.
But I cannot find a legitimate use for freezing, but also modules are nicer than monkey patches.