Skip to content

Instantly share code, notes, and snippets.

@kapcod
Last active July 6, 2017 08:32
Show Gist options
  • Save kapcod/691d471dca618484d3fd to your computer and use it in GitHub Desktop.
Save kapcod/691d471dca618484d3fd to your computer and use it in GitHub Desktop.
Ruby Deep Freeze for Hash and Array classes
# 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