Skip to content

Instantly share code, notes, and snippets.

@camertron
Last active December 21, 2015 19:49
Show Gist options
  • Save camertron/6357004 to your computer and use it in GitHub Desktop.
Save camertron/6357004 to your computer and use it in GitHub Desktop.
Making Ruby Strings Immutable by Default
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