Last active
July 6, 2017 08:32
-
-
Save kapcod/691d471dca618484d3fd to your computer and use it in GitHub Desktop.
Ruby Deep Freeze for Hash and Array classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Adds deep_freeze! method to Hash | |
Hash.class_eval do | |
def deep_freeze! | |
each_value{|val| val.deep_freeze! if val.respond_to?(:deep_freeze!) } | |
freeze | |
end | |
end | |
# Adds deep_freeze! method to Array | |
Array.class_eval do | |
def deep_freeze! | |
each{|val| val.deep_freeze! if val.respond_to?(:deep_freeze!) } | |
freeze | |
end | |
end | |
#We don't want to accidentally freeze global objects like Classes, so only white-listing | |
[String, Range, ActiveRecord::Base, Set].each do |cls| | |
cls.send(:alias_method, :deep_freeze!, :freeze) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment