Feature #8631

Add a new method to ERB to allow assigning the local variables from a hash

Added by Rodrigo Rosenfeld Rosas over 3 years ago. Updated 21 days ago.

Target version:


It would be interesting if ERB could allow a hash instead of a binding for processing the template.

We wouldn't have to do hacks like:

b ={ binding }

feature-8631.pdf - Slide for proposal (27.7 KB) Rodrigo Rosenfeld Rosas, 06/26/2014 12:49 PM

Related issues

Related to CommonRuby - Feature #8643: Add Binding.from_hash Feedback


#1 [ruby-core:56000] Updated by sorah Shota Fukumori over 3 years ago

  • Assignee set to Masatoshi Seki
  • Status changed from Open to Assigned

Assigning to erb maintainer;

IMO, I recommend you to show example mock-code that uses your proposal, to show what interface (API) do you want :)

#2 [ruby-core:56015] Updated by Rodrigo Rosenfeld Rosas over 3 years ago

I didn't propose an API because I don't really care about the API as long as it allows us to provide a hash instead of a binding.

If you want an example API that would satisfy me, I'd be happy if we used the same API (ERB#result). If the argument is a hash, use the keys as the local variables and the values as the variable values.

#3 [ruby-core:56016] Updated by Rodrigo Rosenfeld Rosas over 3 years ago

You can see here how often people want to use a hash to render an ERB template:

And there's no quick way for performing this common procedure. The quickest one seems to be using OpenStruct for that...

#4 [ruby-core:63344] Updated by Rodrigo Rosenfeld Rosas over 2 years ago

Attached slide for proposal

#5 [ruby-core:63426] Updated by Yui NARUSE over 2 years ago

received, thanks!

#6 [ruby-core:64031] Updated by Koichi Sasada over 2 years ago

I think it is easy to implement, but not clear what is "self" on ERB evaluation context.

If you provide binding, self will be binding's self.

#7 [ruby-core:64032] Updated by Yukihiro Matsumoto over 2 years ago

I like the idea, but I have one concern.

The binding also has information about the receiver (which defaults to top-level self).
I am not sure whether it's critical or not.

I hope Seki will address this.


#8 [ruby-core:64037] Updated by Akira Matsuda over 2 years ago

FYI here's an already existing implementation by Seki-san:
Gemified version is here:

#9 Updated by Shyouhei Urabe 7 months ago

#10 [ruby-core:79458] Updated by Nobuyoshi Nakada 21 days ago

Another implementation:

diff --git a/lib/erb.rb b/lib/erb.rb
index 9483711024..9813b4dc71 100644
--- a/lib/erb.rb
+++ b/lib/erb.rb
@@ -887,6 +887,11 @@
   # code evaluation.
   def result(b=new_toplevel)
+    if b.respond_to?(:each_pair)
+      x = new_toplevel
+      b.each_pair {|k, v| x.local_variable_set(k, v)}
+      b = x
+    end
     if @safe_level
       proc {
         $SAFE = @safe_level

Also available in: Atom PDF