Project

General

Profile

Feature #8631

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

Added by Rodrigo Rosenfeld Rosas over 2 years ago. Updated over 1 year ago.

Status:
Assigned
Priority:
Normal
[ruby-core:55985]

Description

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 = OpenStruct.new(hash).instance_eval{ binding }

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

History

#1 [ruby-core:56000] Updated by sorah Shota Fukumori over 2 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 2 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 2 years ago

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

https://github.com/search?q=erb+result+openstruct&type=Code&ref=searchresults

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 1 year ago

Attached slide for proposal

#5 [ruby-core:63426] Updated by Yui NARUSE over 1 year ago

received, thanks!

#6 [ruby-core:64031] Updated by Koichi Sasada over 1 year 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 1 year 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.

Matz.

#8 [ruby-core:64037] Updated by Akira Matsuda over 1 year ago

FYI here's an already existing implementation by Seki-san: https://gist.github.com/seki/6449467
Gemified version is here: https://github.com/takkanm/erb_with_hash

Also available in: Atom PDF