smarkwell / ruby-resourcer

A hash to store resources that degrades to a default resource when the requested isn't available. Developed with Multilingual String resources in mind.

This URL has Read+Write access

ruby-resourcer / Resource.rb
100644 103 lines (85 sloc) 2.466 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 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