From: Robert Klemme Date: 2013-02-16T23:40:18+09:00 Subject: Re: Can not find variable in the current scope! On Sat, Feb 16, 2013 at 1:53 PM, David Unric wrote: > Hello, > > when trying to add tracing output to an erb template I hit the following > issue when trying to find where variable ex_title comes from. I cannot reproduce this issue irb(main):001:0> e = ERB.new '(<%= x %>)' => #, @filename=nil> irb(main):002:0> x = 99 => 99 irb(main):003:0> e.result binding => "(99)" irb(main):004:0> e = ERB.new '(<%= x %>)(<%= local_variables.inspect %>)(<%= local_variables.grep(/x/) %>)' => #, @filename=nil> irb(main):005:0> e.result binding => "(99)([:_erbout, :x, :e, :_])([:x])" Also outside IRB $ ruby -r erb -e 'e=ERB.new("<%= x %>|<%= local_variables.sort.inspect %>");x=99;puts e.result' 99|[:_erbout, :e, :x] $ ruby -r erb -e 'e=ERB.new("<%= x %>|<%= local_variables.grep(/x/) %>");x=99;puts e.result' 99|[:x] > Tried to list all possible variables in the current scope, but there > simply does not exists: > <%= instance_variables.grep(/ex_title/) %> # renders an empty array > <%= global_variables..grep(/ex_title/) %> # renders an empty array > <%= local_variables..grep(/ex_title/) %> # renders an empty array Did you really execute this? I get this irb(main):008:0> f = ERB.new '<%= local_variables..grep(/x/) %>' => #, @filename=nil> irb(main):009:0> f.result binding NoMethodError: undefined method `grep' for main:Object from (erb):1 from /usr/lib/ruby/1.9.1/erb.rb:838:in `eval' from /usr/lib/ruby/1.9.1/erb.rb:838:in `result' from (irb):9 from /usr/bin/irb:12:in `
' $ ruby -r erb -e 'e=ERB.new("<%= x %>|<%= local_variables..grep(/x/) %>");x=99;puts e.result' (erb):1:in `
': undefined method `grep' for main:Object (NoMethodError) from /usr/lib/ruby/1.9.1/erb.rb:838:in `eval' from /usr/lib/ruby/1.9.1/erb.rb:838:in `result' from -e:1:in `
' If I omit the second dot I get irb(main):010:0> f = ERB.new '<%= local_variables.grep(/x/) %>' => #, @filename=nil> irb(main):011:0> f.result binding => "[:x]" > <%= instance_variables.sort %> # renders array with many elements > <%= global_variables.sort %> # renders array with many elements > <%= local_variables.sort %> # renders array with many elements > > Whereas ex_title variable provably does exists: > <%= ex_title %> # renders value "Categories - Online > store" > <%= ex_title.class %> # renders "String" > <%= ex_title.object_id %> # renders "15825900" > > Where else can be found if not in global, local or instance variables ? You would have to show us how you evaluate those ERB templates. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/