Method for checking syntax

Very good point! I'd prefer my approach with the lambda because that
does not execute the code and it also gives you a handle to the code
for later execution. That avoids a second compilation.

Cheers

robert

···

On Sun, Dec 8, 2013 at 8:57 PM, Joel VanderWerf <joelvanderwerf@gmail.com> wrote:

On 12/06/2013 01:49 PM, Ryan Davis wrote:

def check_syntax src
   catch(:good) do
     eval("throw :good; #{src}")
   end
   true
rescue SyntaxError
   false
end

Use BEGIN to be a bit safer:

def check_syntax_unsafe src

  catch(:good) do
    eval("throw :good; #{src}")
  end
  true
rescue SyntaxError
  false
end

def check_syntax_safe src
  catch(:good) do
    eval("BEGIN {throw :good}; #{src}")

  end
  true
rescue SyntaxError
  false
end

puts "UNSAFE"
p check_syntax_unsafe %{
  BEGIN {puts "haha"}
}

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Only if you really trust the input code...

code = '1 + 2 }; puts "haha"; proc {'
compiled = eval("lambda { #{code} }")
p compiled.call

···

On 12/08/2013 11:57 PM, Robert Klemme wrote:

Very good point! I'd prefer my approach with the lambda because that
does not execute the code and it also gives you a handle to the code
for later execution. That avoids a second compilation.

Dang! I should think more next time.

Cheers

robert

···

On Mon, Dec 9, 2013 at 9:47 PM, Joel VanderWerf <joelvanderwerf@gmail.com> wrote:

On 12/08/2013 11:57 PM, Robert Klemme wrote:

Very good point! I'd prefer my approach with the lambda because that
does not execute the code and it also gives you a handle to the code
for later execution. That avoids a second compilation.

Only if you really trust the input code...

code = '1 + 2 }; puts "haha"; proc {'

compiled = eval("lambda { #{code} }")
p compiled.call

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

+1 cleverness for Joel VanderWerf!

Code injection on the go!

(I didn't understand it at first sight. I've had to fire up an irb
session to realize how it broke Robert Klemme's approach).

···

On Mon, Dec 9, 2013 at 6:53 PM, Robert Klemme <shortcutter@googlemail.com> wrote:

On Mon, Dec 9, 2013 at 9:47 PM, Joel VanderWerf > <joelvanderwerf@gmail.com> wrote:

On 12/08/2013 11:57 PM, Robert Klemme wrote:

Very good point! I'd prefer my approach with the lambda because that
does not execute the code and it also gives you a handle to the code
for later execution. That avoids a second compilation.

Only if you really trust the input code...

code = '1 + 2 }; puts "haha"; proc {'

compiled = eval("lambda { #{code} }")
p compiled.call

Dang! I should think more next time.

Cheers

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/