# Purpose: FreeBASE properties Manager. # # $Id: properties.rb,v 1.1 2002/02/06 03:24:38 richkilmer Exp $ # # Authors: Rich Kilmer # Contributors: # # This file is part of the FreeRIDE project # # This application is free software; you can redistribute it and/or # modify it under the terms of the Ruby license defined in the # COPYING file. # # Copyright (c) 2001 Rich Kilmer. All rights reserved. # require 'rexml/document' module FreeBASE ## # The Properties class sits on top of the databus # and persists the tree of values in an xml file # class Properties ## # Creates a new Properties # # name:: [String] The name of this properties file # version:: [String] The version of this properties file # base_slot:: [FreeBASE::DataBus::Slot] The base slot of the branch to persist # filespec:: [String] The file to store the properties in # def initialize(name, version, base_slot, filespec) @base_slot = base_slot @filespec = filespec @name = name @version = version @base_slot.manager = self @base_slot.subscribe self read end ## # Event handler for Slot change notifications # see:: FreeRIDE::DataBus::Slot # def databus_notify(event, slot) write if event == :notify_data_set end ## # Gets the property value # # path:: [String] the property path # return:: [String] the property value # def [](path) return @base_slot[path].data end ## # Sets the property value and persists the properties # # path:: [String] the property path # value:: [to_s] the property value # def []=(path, value) value = value.to_s unless value.kind_of? String @base_slot[path].data = value end private ## # Read and parse the properties file # def read return unless File.exist?(@filespec) file = File.new(@filespec) doc = REXML::Document.new file doc.root.each_element("slot") do |element| read_slot(@base_slot, element) end file.close end def read_slot(root, element) slot = root[element.attributes["name"]] slot.data = element.text.strip element.each_element("slot") do |element| read_slot(slot, element) end end ## # Write the properties to the filespec # def write file = File.new(@filespec, "w+") @doc = REXML::Document.new "" @base_slot.each_slot do |slot| write_slot(slot, @doc.root) end @doc.write file file.close end def write_slot(slot, root) n_element = root.add_element("slot", {"name"=>slot.name}) n_element.text = slot.data slot.each_slot do |child| write_slot(child, n_element) end end end end