# Saving and Restoring a GTK:TreeModel

**URL:** <https://www.ruby-forum.com/t/saving-and-restoring-a-gtk-treemodel/186655>\
**Category:** Ruby\
**Created:** [April 10, 2010, 6:27pm UTC](https://www.ruby-forum.com/t/saving-and-restoring-a-gtk-treemodel/186655 "2010-04-10T18:27:26Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Andreas\_Drop](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a87d85/32.png) [@Andreas\_Drop](https://www.ruby-forum.com/u/Andreas_Drop)\
**Post date:** [April 10, 2010, 6:27pm UTC](https://www.ruby-forum.com/t/saving-and-restoring-a-gtk-treemodel/186655/1 "2010-04-10T18:27:26Z")

</div>

-----BEGIN PGP SIGNED MESSAGE-----  
Hash: SHA1

Hi,

Here is a small snippet of my code that saves and restores a  
Gtk::Treemodel to/from a file. Just because i searched a while, before i  
decided, i had to do it all by myself

The code is without any error handling, is tailored for a special  
TreeStore and saves a model with two columns( string, string), which  
should be no problem to change, if more columns or other datatypes  
occure.

class Tagtree

def self.store treemodel, file\_name  
file = File.new(file\_name,‘w+’)  
treemodel.each do |model, path, iter|  
file.puts path.to\_s \<\< “|” \<\< iter[0] \<\< “|” \<\< iter[1]  
end  
file.close  
end

def self.load model, file\_name  
anchors=Array.new  
olditer, depth =nil, 0  
IO.foreach(file\_name) do |line|  
fields=line.split(‘|’)  
position=fields[0].split(‘:’)  
anchors[depth] = olditer  
entry=model.append(anchors[position.length-1])  
entry[0]=fields[1]  
entry[1]=fields[2]  
depth, olditer = position.length, entry  
end  
end  
end

Usage:

Tagtree.store(treemodel,“filetostore”)  
Tagtree.loade(treemodel,“filetostore”)

-----BEGIN PGP SIGNATURE-----  
Version: GnuPG v1.4.9 (GNU/Linux)  
Comment: Using GnuPG with Mozilla - [http://enigmail.mozdev.org](http://enigmail.mozdev.org)

iEYEARECAAYFAkvAprkACgkQjsqVO1/Pdpw5GgCgp4sxA+du04rlmKlTclM/9XmB  
W7YAoKb16OjNaAICIE/si2HoL+dBdXlg  
=4YI4  
-----END PGP SIGNATURE-----
