ruby-changes:46775
From: k0kubun <ko1@a...>
Date: Fri, 26 May 2017 00:38:29 +0900 (JST)
Subject: [ruby-changes:46775] k0kubun:r58891 (trunk): erb.rb: Add ERB#result_with_hash
k0kubun 2017-05-26 00:38:25 +0900 (Fri, 26 May 2017) New Revision: 58891 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=58891 Log: erb.rb: Add ERB#result_with_hash [ruby-core:55985] [Feature #8631] [fix GH-1623] Modified files: trunk/lib/erb.rb trunk/test/erb/test_erb.rb Index: lib/erb.rb =================================================================== --- lib/erb.rb (revision 58890) +++ lib/erb.rb (revision 58891) @@ -889,6 +889,16 @@ class ERB https://github.com/ruby/ruby/blob/trunk/lib/erb.rb#L889 end end + # Render a template on a new toplevel binding with local variables specified + # by a Hash object. + def result_with_hash(hash) + b = new_toplevel + hash.each_pair do |key, value| + b.local_variable_set(key, value) + end + result(b) + end + ## # Returns a new binding each time *near* TOPLEVEL_BINDING for runs that do # not specify a binding. Index: test/erb/test_erb.rb =================================================================== --- test/erb/test_erb.rb (revision 58890) +++ test/erb/test_erb.rb (revision 58891) @@ -564,6 +564,35 @@ EOS https://github.com/ruby/ruby/blob/trunk/test/erb/test_erb.rb#L564 assert_equal(flag, erb.result) end end + + def test_result_with_hash + erb = @erb.new("<%= foo %>") + assert_equal("1", erb.result_with_hash(foo: "1")) + end + + def test_result_with_hash_does_not_use_caller_local_variables + erb = @erb.new("<%= foo %>") + foo = 1 + assert_raise(NameError) { erb.result_with_hash({}) } + end + + def test_result_with_hash_does_not_modify_caller_binding + erb = @erb.new("<%= foo %>") + erb.result_with_hash(foo: "1") + assert_equal(false, binding.local_variable_defined?(:foo)) + end + + def test_result_with_hash_does_not_modify_toplevel_binding + erb = @erb.new("<%= foo %>") + erb.result_with_hash(foo: "1") + assert_equal(false, TOPLEVEL_BINDING.local_variable_defined?(:foo)) + end + + # This depends on the behavior that #local_variable_set raises TypeError by invalid key. + def test_result_with_hash_with_invalid_keys_raises_type_error + erb = @erb.new("<%= 1 %>") + assert_raise(TypeError) { erb.result_with_hash({ 1 => "1" }) } + end end class TestERBCoreWOStrScan < TestERBCore -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/