Feature #8631

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

Added by rosenfeld (Rodrigo Rosenfeld Rosas) almost 4 years ago. Updated 3 months 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) rosenfeld (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 (sorah Shota Fukumori) almost 4 years ago

  • Assignee set to seki (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 rosenfeld (Rodrigo Rosenfeld Rosas) almost 4 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 rosenfeld (Rodrigo Rosenfeld Rosas) almost 4 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 rosenfeld (Rodrigo Rosenfeld Rosas) almost 3 years ago

Attached slide for proposal

#5 [ruby-core:63426] Updated by naruse (Yui NARUSE) almost 3 years ago

received, thanks!

#6 [ruby-core:64031] Updated by ko1 (Koichi Sasada) almost 3 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 matz (Yukihiro Matsumoto) almost 3 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 matsuda (Akira Matsuda) almost 3 years ago

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

#9 Updated by shyouhei (Shyouhei Urabe) 9 months ago

#10 [ruby-core:79458] Updated by nobu (Nobuyoshi Nakada) 3 months 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