erb and scope

W

Wybo Dekker

Why does this not work (bar->undefined) and what's a better way to do it?:

require 'erb'

FOO = 'Hello <%= bar %>'
class Foo
def doit
bar = 'World!'
puts ERB.new(FOO).result
end
end

Foo.new.doit

I need to use $bar instead of bar to get it going...
 
S

Stefan Lang

Why does this not work (bar->undefined) and what's a better way to
do it?:

require 'erb'

FOO = 'Hello <%= bar %>'
class Foo
def doit
bar = 'World!'
puts ERB.new(FOO).result

replace above line with:

puts ERB.new(FOO).result(binding)
end
end

Foo.new.doit

Regards,
Stefan
 
X

Xavier Noria

Wybo Dekker:
[erb]
I need to use $bar instead of bar to get it going...

@bar will do it, too, and that's maybe the best way to do it.

[Other poster suggests passing binding.]

I have always wondered why erb does not provide in addition the
possibility to pass a regular hash. In general I don't want to design
my objects or scopes around a template. Is there a rationale behind
that?

-- fxn
 
J

James Edward Gray II

That helps (although I don't understand it yet, but I'll find out),
thanks!

ERb templates are resolved in the scope of some "binding". They have
access to the variables in that binding. There is a private method
on Object (universally available) called binding(), which just
returns a Binding object for the current scope. By handing that to
ERb, you can control what it can access.

Hope that helps.

James Edward Gray II
 
J

James Edward Gray II

Wybo Dekker:
[erb]
I need to use $bar instead of bar to get it going...

@bar will do it, too, and that's maybe the best way to do it.

[Other poster suggests passing binding.]

I have always wondered why erb does not provide in addition the
possibility to pass a regular hash. In general I don't want to
design my objects or scopes around a template. Is there a rationale
behind that?

I imagine the reason is because ERb uses eval() under the hood and
the tool eval() gives us is Binding. We should be able to use that
to do pretty much what you want though:
=> "This is ERb using One and Two."

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top