From: Stefan Kaes Date: 2005-03-16T15:01:55+09:00 Subject: Re: eval/binding question Yukihiro Matsumoto wrote: >Hi, > >In message "Re: eval/binding question" > on Wed, 16 Mar 2005 02:45:41 +0900, Stefan Kaes writes: > >|In the real environment, the names of the locally assigned variables can >|not be determined in advance, of course. > >I'm sorry to say you can't pre-compile eRB allowing local variable set >not determined in advance. I know allowing this will make your >program 25% faster, but this also would make any other programs >slower. > > I fail to see why it would make other code slower. I am convinced with a proper compiler implementation there would'nt be any speed difference for local variables introduced via explicit assignment. Access to predeclared variables would use an optimized access method, whereas access to variable names whose declaration point cannot be determined by statical program analysis would use a less efficient access method. >If you have limited set of local variables, you can do something like: > > require 'erb' > > class Test > def initialize(path, *lv) > @erb = ERB.new(File.read(path), nil, '%') > @locals = {} > evalstr = "def run_erb\n" + > lv.collect{|k| "#{k} = @locals[\"#{k}\"]\n"}.join + > "#{@erb.src}\n_erbout\nend\n" > print evalstr, "\n\n" > eval evalstr, nil, path, 0 > end > def values(hash) > @locals.update(hash) > hash.each {|k,v| > self.instance_variable_set("@#{k}", v) > } > end > end > > t = Test.new("/tmp/test.rhtml", 'mumu') > t.values("mumu" => "HELLO") > print t.run_erb > > matz. > > That's simlar to the way I "solved" "my problem" already. Thanks. -- stefan