Erb and scope


#1

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…


#2

On Sunday 11 December 2005 12:08, Wybo D. wrote:

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


#3

Wybo D.:
[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.

Malte


#4

On Sun, 11 Dec 2005, Stefan L. wrote:

puts ERB.new(FOO).result

replace above line with:

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

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


#5

On Dec 11, 2005, at 13:32, Malte M. wrote:

Wybo D.:
[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


#6

On Dec 11, 2005, at 6:36 AM, Wybo D. wrote:

On Sun, 11 Dec 2005, Stefan L. wrote:

puts ERB.new(FOO).result

replace above line with:

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

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 G. II


#7

On Dec 11, 2005, at 7:49 AM, Xavier N. wrote:

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:

require “erb”
=> true

class Template
def initialize( variables )
variables.each { |name, value| instance_variable_set("@#
{name}", value) }

end

?> def resolve( template )

ERB.new(template).result(binding)

end
end
=> nil

t = Template.new(:one_var => “One”, :two_var => “Two”)
=> #<Template:0x3253dc @two_var=“Two”, @one_var=“One”>

t.resolve(“This is ERb using <%= @one_var %> and <%= @two_var %>.”)
=> “This is ERb using One and Two.”

James Edward G. II