Programming With Ruby Episode 17, Getting Advanced
Series: Ruby Programming
Covered In This Episode:- Symbols
- eval
- Bindings
- Running Other Programs
- Safe Levels
my_method
. By using the binding method, we can make variable scopes portable!
Running Other Programs
There comes a time when you will want to be able to run a program from
Ruby, maybe you want to automate something, or simply get the output
from an external program.
There are a few ways of doing this.
The first is with the method exec, which runs an external programs,
and quits the Ruby script at the same time:
[source language="ruby"]
exec('ls') # dir on windows
# Program never gets here
[/source]
There is also system, which does the same thing, but doesn't quit the
Ruby script, and returns true or false if the program was successful:
[source language="ruby"]
system('ls') # dir on windows
# we do get this far
[/source]
Finally we have the "back-tick" `. Which looks like a sideways single
quote. On my keyboard it is above the tab key. You surround your
command in the back-ticks, like you would for a sting. Unlike the other
two methods of running a program, this method also returns the output
of the program you run.
[source language="ruby"]
variable = `ls`
[/source]
Safe Levels
If you are running a Ruby interpreter online or in another environment
where users can enter in and run Ruby code. They hold the ability to
wreak havoc on your system.
The way to prevent this from happening is by using safe levels. Safe
levels are a way of preventing the user from getting access to the
file system, or changing any variables that the program has.
You set safe levels by setting the $SAFE variable. By default it is
set to zero.
[source language="ruby"]
$SAFE = 4
[/source]
Ruby "taints" objects that could be dangerous.
There are five different safe levels.
0 => The default, you can do anything
1 => Can't use environment variable, eval, load, require, and more.
2 => Same as above and also can't use files
3 => All objects created are tainted, can't be untainted
4 => You can do almost nothing... Can't modify the untainted, can't
use exit. Basically completely safe and sand-boxed.
That brings us to the end of the episode. If you liked these videos,
please donate. It costs me in both money and time to make them.
If you have any questions, comments, or suggestions please don't
hesitate to leave a comment on this page or email me at
[email protected]
Thanks for watching, goodbye!
Comments
Beck on
I love this site! You make writing Ruby code look so simple. Right now I'm trying to figure out arrays. My class is going crazy trying to google it, but nobody's had much luck. Thanks for all your videos! I'd donate...but I'm 17 and don't have a credit, debit or paypal account. ~Meg61 ;-)