On Sat, Dec 07, 2002 at 02:54:17AM +0900, Chris Pine wrote:
> Hello,
> 
> I've got a kind of tricky question.  For my tutorial there are lots of code
> samples, and I usually want to display the output of them in the page.  I'd
> like to automate this.  I'm generating all of the pages in mod_ruby.
> 
> Because there are so many of them, though, I'd like them to be safe from
> each other... I guess each one should be in it's own namespace?  (I don't
> know much about namespaces... better not cover that in the tutorial!)
> 
> I'm hoping for something like this:
> 
>   code = "puts 'hello'"
>   output = executeCode (code)
>   output  #  should be "hello\n"
> 
> Each code sample is supposed to be it's own program, so I don't want any
> possibilities of variables showing up in code samples further on down the
> page, and *certainly* not on subsequent calls to that page!  Does any one
> know how I could do this?

Well, you could just call ruby in a sub-shell. The easiest way would be to
use the backtick operators. The naive implementation might use ruby -e, but
you might want to write the code to some sort of tmp file and then execute
that file.

def executeCode(code)
  ecode = code.gsub('"', '\"')
  return `ruby -e "#{ecode}"`
end

code = %Q(puts "Hello")

output = executeCode(code)

puts code
puts "\nReturned:\n#{output}"
 

> OK, if you can handle that, how about this...
> 
> Many of the programs require input.  Is there a way I could queue up the
> input I want to send the program before it is run?  Something like this:
> 
>   code = <<-'END_CODE
>     str1 = gets
>     str2 = gets
>     puts str1
>     puts str2
>   END_CODE
> 
>   input = "hello\n"+
>           "hi\n"
> 
>   #  Then I'll strip the leading whitespace out of the code.
> 
>   output = executeCode (code, input)

If you went writing the code as well as the input to temporary files,
the backtick command in executeCode above might go to
  ruby tmpcode.rb < tmpinput.rb

> 
> If you can do that, you have helped me greatly.  However, the *perfect*
> solution would be a little bit trickier...
> 
> I would like to echo the input back into the output in the right place (just
> like would happen when running such a program from the commandline), and
> surround it in special <span> tags so I can change it's style from the
> 'output' style to the 'input' style.

Now that, I'll have to think about...

-- 
Alan Chen
Digikata Computing
http://digikata.com