Last active
December 21, 2015 19:49
-
-
Save camertron/6357004 to your computer and use it in GitHub Desktop.
Making Ruby Strings Immutable by Default
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
module BeforeMethodHook | |
def before(*names) | |
names.each do |name| | |
m = instance_method(name) | |
define_method(name) do |*args, &block| | |
yield self | |
m.bind(self).call(*args, &block) | |
end | |
end | |
end | |
end | |
class MutableString < String | |
def mutable? | |
true | |
end | |
def freeze | |
raise "Can't freeze a mutable string, silly." | |
end | |
def frozen? | |
false | |
end | |
end | |
class String | |
extend BeforeMethodHook | |
before(*instance_methods) do |obj| | |
unless obj.mutable? | |
unless @freeze_mutex | |
@freeze_mutex = true | |
obj.freeze unless obj.frozen? | |
@freeze_mutex = false | |
end | |
end | |
end | |
def mutable? | |
false | |
end | |
def frozen? | |
true | |
end | |
end | |
str = "hello" | |
begin | |
str.upcase! | |
puts "Something went wrong, the previous operation should have caused an exception" | |
rescue => e | |
puts "Error: #{e.message}" | |
end | |
str = MutableString.new("hello") | |
str << "world" | |
puts str |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment