How can I convert this PHP script to Ruby? (build tree from tabbed string)
- by Jon Sunrays
I found this script below online, and I'm wondering how I can do the same thing with a Ruby on Rails setup.
So, first off, I ran this command: rails g model Node node_id:integer title:string
Given this set up, how can I make a tree from a tabbed string like the following?
<?php
// Make sure to have "Academia" be root node with nodeID of 1
$data = "
Social sciences
Anthropology
Biological anthropology
Forensic anthropology
Gene-culture coevolution
Human behavioral ecology
Human evolution
Medical anthropology
Paleoanthropology
Population genetics
Primatology
Anthropological linguistics
Synchronic linguistics (or Descriptive linguistics)
Diachronic linguistics (or Historical linguistics)
Ethnolinguistics
Sociolinguistics
Cultural anthropology
Anthropology of religion
Economic anthropology
Ethnography
Ethnohistory
Ethnology
Ethnomusicology
Folklore
Mythology
Political anthropology
Psychological anthropology
Archaeology
...(goes on for a long time)
";
//echo "Checkpoint 2\n";
$lines = preg_split("/\n/", $data);
$parentids = array(0 => null);
$db = new PDO("host", 'username', 'pass');
$sql = 'INSERT INTO `TreeNode` SET ParentID = ?, Title = ?';
$stmt = $db->prepare($sql);
foreach ($lines as $line) {
if (!preg_match('/^([\s]*)(.*)$/', $line, $m)) {
continue;
}
$spaces = strlen($m[1]);
//$level = intval($spaces / 4); //assumes four spaces per indent
$level = strlen($m[1]); // if data is tab indented
$title = $m[2];
$parentid = ($level > 0 ? $parentids[$level - 1] : 1); //All "roots" are children of "Academia" which has an ID of "1";
$rv = $stmt->execute(array($parentid, $title));
$parentids[$level] = $db->lastInsertId();
echo "inserted $parentid - " . $parentid . " title: " . $title . "\n";
}
?>