James Gray
12/11/2005 4:23:00 PM
On Dec 11, 2005, at 7:49 AM, Xavier Noria wrote:
> On Dec 11, 2005, at 13:32, Malte Milatz wrote:
>
>> 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:
>> 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 Gray II