Todd Benson
2/21/2008 8:04:00 PM
On Thu, Feb 21, 2008 at 1:44 PM, Andrew Chen <hangfei@gmail.com> wrote:
> Hi,
>
> I use the instance_eval to merge template file and parameter files.
>
> >cat param.txt
> name="John"
> >cat tmpl.txt
> my name is: <%= name %>
>
> >cat template.rb
> #!/usr/bin/env ruby
> require 'erb'
>
name = nil
> instance_eval(File.read('param.txt'))
> puts ERB.new(File.read("tmpl.txt")).result(binding)
>
> puts name
>
> >template.rb
> my name is: John
> template.rb:7: undefined method `name' for main:Object (NoMethodError)
>
>
> Where is the variable "name" set to? How to access it?
> It must be somewhere, since it is used in the tmpl.txt file.
>
> Is there any "magic" namespace in Ruby?
It's just a scope issue. If you use name = nil like I did above you
should be okay. I wonder, though, why you would want to
#instance_eval instead of using #load.
Also, some rubyists advocate using the block method of File.open as
well. I'm not sure if File.read closes the file automatically.
hth,
Todd