From: Rick DeNatale Date: 2008-03-12T11:26:35+09:00 Subject: Re: setting local variables via eval 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 Program exited. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/