From: Joel VanderWerf Date: 2008-03-12T11:57:09+09:00 Subject: Re: setting local variables via eval Rick DeNatale wrote: > On 3/11/08, Joel VanderWerf wrote: >> Rick DeNatale wrote: >> > On 3/11/08, ara howard wrote: >> >> thought some here might appreciate this >> >> >> >> http://drawohara.com/post/28514698 >> >> >> >> kind regards >> >> >> >> a @ http://codeforpeople.com/ >> > >> > No need for Object#context >> > >> > class View >> > def initialize template >> > @template = template >> > end >> > >> > def render locals = {} >> > context = binding >> > locals.each do |k, v| >> > var = k >> > value = "ObjectSpace._id2ref #{ v.object_id }" >> > definition = "#{ var } = #{ value }" >> > eval definition, context >> > end >> > double_quoted_heredoc = ['<<__template__', @template, >> > '__template__'].join("\n") >> > eval double_quoted_heredoc, context >> > end >> > end >> > >> > view = View.new ' #{ x + y } ' >> > >> > puts view.render(:x => 40, :y => 2) #=> 42 >> > >> > Works just as well. >> >> >> Not quite. >> >> view = View.new ' #{ x + y } #{locals} ' >> puts view.render(:x => 40, :y => 2) # ==> 42 x40y2 > > Not on my machine: > > RubyMate r8136 running Ruby r1.8.6 > (/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby) >>>> untitled > > 42 Hm. Unless there are at least 2 spaces after the Answer (to the Ultimate Question et al), you're not running my two lines of code there... (Even if locals was nil, you'd still get two spaces.) -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407