# Allows for arbitary resources to be mapped to an ID and a tag.
# If a requested tag is not available on an ID, then the default data is returned.
# The default data is located at the nil tag.
#
#
# An example usage is for String storage in an application that needs to be multilingual.
# In such a case, I set the ID to the string representing the concept to be presented,
# the tag the language of the data, and the data to string itself.
#
# ==== Example
# require 'Resource'
# r = Resource.new
# r.set(1,"Hello","en")
# r.set(1,"Hola","es")
# r.set(1,"Bork Bork!")
# r.get(1) #<= "Bork Bork!"
# r.setDefaultTag("en")
# r.get(1) #<= "Hello"
# r.get(1,"es") #<= "Hola"
# r.save("file")
#
# Author:: Scott Markwell - mailto:scott.markwell@gmail.com - http://blurryworks.com
# License:: Public Domain - No warrenty is implied or given. Code can be modified freely and distrubted with no restrictions.
require "yaml"
# ==== Warning / Security Concern
# No checking is done on the validity of the YAML document loaded
# Please only load known well formed documents, and not documents provided by un-trusted users.
class Resource
# Normally the default tag when no tag is provided is nil.
# By modiying this attribute, you can inject another tag to be checked
# before checking nil. By default this is nil.
attr_accessor :defaultTag
#Returns a new instance loaded with the passed YAML file.
def self.load(file)
ret = self.new()
ret.load(file)
ret
end
def reset
@data = nil
return
end
def load(file)
self.reset
File.open(file,"r") {|yf| @data = YAML::load(yf)}
end
def save(file)
File.open(file,"w") {|yf| yf.puts YAML::dump(@data)}
end
def get(key,tag=nil)
if @data == nil
return nil
end
if @data[key] == nil
return nil
end
if tag == nil && @defaultTag != nil
tag = @defaultTag
end
ret = @data[key][tag]
if ret == nil
ret = @data[key][@defaultTag]
if ret == nil
ret = @data[key][nil]
end
end
return ret
end
def set(key,data,tag=nil)
if @data == nil
@data = {}
end
if @data[key] == nil
@data[key] = {}
end
if(tag == nil && @defaultTag != nil)
tag = @defaultTag
end
@data[key][tag] = data
end
# Returns a YAML Dump
def dump
YAML::dump(@data)
end
end