12.10.05

Ruby tricks: escaping/unescaping

Posted in Uncategorized, Mac OS X, computers, TextMate, ruby/rails at 2:20 pm by Haris

I am starting to really like Ruby! I was working on my plugin, for Gregarius, and I found myself having to often have the php code spit out javascript code using echo. So something like:

function myinsert(node) {
    var ob = document.getElementById("maindiv");
    ob.setAttribute('style','display:none');
}

would be converted to:

."\tfunction myinsert(node) {\n"
."\t\tvar ob = document.getElementById(\"maindiv\");\n"
."\t\tob.setAttribute('style','display:none');\n"
."\t}\n"

to be inserted as part of an echo command. Effectively the issue here is how to quickly escape and unescape characters. So after manually converting things, I decided to create two custom commands in TextMate to do this for me. Effectively, using Ruby, each of these can be done in one (!) single line:

STDIN.each_line {|line| puts("." + line.dump);};

for converting from javascript to echo-form, and:

STDIN.each_line {|line| puts(eval("\"#{line.strip.slice(2..-2)}\"")); };

to go the other way, though be careful with the second one, I understand it could allow arbitrary code to be executed.

Later

Leave a Comment