From: ara howard Date: 2008-03-12T00:52:28+09:00 Subject: Re: setting local variables via eval On Mar 11, 2008, at 5:28 AM, Robert Dober wrote: > Ara > > Obviously I miss something, but I have the feeling that this > simplification still works, which use cases did I miss? > The idea is crazy of course :) > > class View > def initialize template > @template = template > end > > def render locals = {} > context = binding > locals.each do |k, v| > definition = "#{ k } = #{ v }" > 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 > > Cheers > Robert cfp2:~ > cat a.rb require 'yaml' locals = { 'K' => 'or any thing else really', 'k' => %w( list of words ), } context = binding locals.each do |k, v| begin definition = "#{ k } = #{ v }" y 'k' => k, 'v' => v, 'definition' => definition eval definition, context rescue Object => e y 'error' => "#{ e.message } (#{ e.class })" end end cfp2:~ > ruby a.rb --- v: - list - of - words k: k definition: k = listofwords --- error: undefined local variable or method `listofwords' for main:Object (NameError) --- v: or any thing else really k: K definition: K = or any thing else really --- error: |- compile error b.rb:8: syntax error, unexpected kOR K = or any thing else really ^ (SyntaxError) ;-)) a @ http://drawohara.com/ -- sleep is the best meditation. h.h. the 14th dalai lama