Skip to content

Commit

Permalink
erb.rb: Add locals option to set local variables
Browse files Browse the repository at this point in the history
to `ERB#result` method.

[ruby-core:55985] [Feature #8631]
  • Loading branch information
k0kubun committed May 19, 2017
1 parent 92690b6 commit f1fc68b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/erb.rb
Expand Up @@ -885,8 +885,18 @@ def run(b=new_toplevel)
#
# _b_ accepts a Binding object which is used to set the context of
# code evaluation.
# _locals_ accepts a Hash object which is used to set local variables
# on the Binding object.
#
def result(b=new_toplevel)
def result(b=new_toplevel, locals: nil)
if locals
shadows = locals.keys.select { |l| b.local_variable_defined?(l) }
b = eval("proc { |#{shadows.join(',')}| self.send(:binding) }.call", b)
locals.each_pair do |key, value|
b.local_variable_set(key, value)
end
end

if @safe_level
proc {
$SAFE = @safe_level
Expand Down
31 changes: 31 additions & 0 deletions test/erb/test_erb.rb
Expand Up @@ -540,6 +540,37 @@ def test_frozen_string_literal
assert_equal(flag, erb.result)
end
end

def test_result_with_locals
erb = @erb.new("<%= foo %>")
assert_equal("1", erb.result(locals: { foo: "1" }))

erb = @erb.new("<%= foo %>")
b = Struct.new(:foo).new("1").instance_eval { binding }
assert_equal("2", erb.result(b, locals: { foo: "2" }))

erb = @erb.new("<%= foo %><%= bar %>")
b = Struct.new(:foo).new("1").instance_eval { binding }
assert_equal("12", erb.result(b, locals: { bar: "2" }))
end

def test_result_with_locals_does_not_modify_given_binding
EnvUtil.suppress_warning do
a = 1
assert_equal("2", @erb.new("<%= a %>").result(binding, locals: { a: 2 }))
assert_equal(1, a)
end
end

def test_result_with_locals_named_binding
b = binding
binding = 1
assert_equal("2", @erb.new("<%= binding %>").result(b, locals: { binding: 2 }))
end

def test_result_with_invalid_name_locals
assert_raise(NameError) { @erb.new("").result(locals: { :'foo-bar' => 1 }) }
end
end

class TestERBCoreWOStrScan < TestERBCore
Expand Down

0 comments on commit f1fc68b

Please sign in to comment.