https://bugs.ruby-lang.org/https://bugs.ruby-lang.org/favicon.ico?17113305112016-01-20T09:50:55ZRuby Issue Tracking SystemRuby master - Feature #12008: Immutable object graphs (a.k.a. deep freeze)https://bugs.ruby-lang.org/issues/12008?journal_id=561902016-01-20T09:50:55Znormalperson (Eric Wong)normalperson@yhbt.net
<ul></ul><p><a href="mailto:bascule@gmail.com" class="email">bascule@gmail.com</a> wrote:</p>
<blockquote>
<p>I think immutable state has huge benefits for a lot of areas, most<br>
notably concurrency and security.</p>
</blockquote>
<p>Agree. Maybe something along the lines of the following?</p>
<pre><code> module DeepFreezable
def deep_freeze_check!(obj)
obj.frozen? or raise TypeError, "#{obj.inspect} not frozen in #{inspect}"
end
def ivar_deep_frozen?
instance_variables.each do |iv|
deep_freeze_check!(instance_variable_get(iv))
end
end
end
class Array
include DeepFreezable
def deep_freeze
ivar_deep_frozen?
each { |obj| deep_freeze_check!(obj) }
freeze
end
end
class String
include DeepFreezable
def deep_freeze
ivar_deep_frozen?
freeze
end
end
class Hash
include DeepFreezable
def deep_freeze
ivar_deep_frozen?
each do |key, val|
deep_freeze_check!(key)
deep_freeze_check!(val)
end
freeze
end
end
require 'test/unit'
class TestDeepFreeze < Test::Unit::TestCase
def test_deep_freeze
assert_predicate({}.deep_freeze, :frozen?)
assert_raise(TypeError) { {'foo' => 'bar'.dup }.deep_freeze }
assert_predicate({'foo' => 'bar'.freeze }.deep_freeze, :frozen?)
assert_raise(TypeError) { %w(a b c).map(&:dup).deep_freeze }
assert_predicate(%w(a b c).map(&:freeze).deep_freeze, :frozen?)
s = String.new
s.instance_eval { @foo = 'bar'.dup }
assert_raise(TypeError) { s.deep_freeze }
s.freeze
assert_raise(TypeError) { s.deep_freeze }
s.instance_variable_get(:@foo).freeze
assert_predicate s.deep_freeze, :frozen?
end
end
</code></pre>
<p>Unsubscribe: <a href="mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe" class="email">mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe</a><br>
<a href="http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core" class="external">http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core</a></p> Ruby master - Feature #12008: Immutable object graphs (a.k.a. deep freeze)https://bugs.ruby-lang.org/issues/12008?journal_id=789272019-06-27T22:29:35Zjeremyevans0 (Jeremy Evans)merch-redmine@jeremyevans.net
<ul><li><strong>Tracker</strong> changed from <i>Bug</i> to <i>Feature</i></li><li><strong>Backport</strong> deleted (<del><i>2.0.0: UNKNOWN, 2.1: UNKNOWN, 2.2: UNKNOWN, 2.3: UNKNOWN</i></del>)</li></ul>