Class: KerbalDyn::Data
- Inherits:
-
Object
- Object
- KerbalDyn::Data
- Defined in:
- lib/kerbaldyn/data.rb
Overview
:nodoc: all
A class for doing the work of getting and maintaining singletons of data resources.
NOTE: There is NO reason a client to the library shoudl be in here; indeed, this is likely to drastically change, so using this class directly will result in trouble later.
Constant Summary collapse
- FILE_MAP =
Files added here are automatically recognized by the fetch method. Files must be in the data directory.
{ :planet_data => 'planet_data.json' }
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
-
#key ⇒ Object
readonly
Returns the value of attribute key.
Class Method Summary collapse
-
.fetch(key) ⇒ Object
Fetch a data singleton by the stored key.
-
.registry ⇒ Object
A method for directly getting the registry; this shoudl typically be treated as private.
Instance Method Summary collapse
-
#initialize(key, data_file_name) ⇒ Data
constructor
Initialize with the given key and data file name (in the data directory).
Constructor Details
#initialize(key, data_file_name) ⇒ Data
Initialize with the given key and data file name (in the data directory). This does NOT auto-add to the registry. Fetch will do so for entries in FILE_MAP.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/kerbaldyn/data.rb', line 35 def initialize(key, data_file_name) # Get a handle on the file. data_file = Pathname.new(__FILE__).dirname + 'data' + data_file_name.to_s raise ArgumentError, "No such file #{data_file.to_s}" unless data_file.exist? # Parse @data = case data_file.extname when '.json' JSON.parse( data_file.read, :symbolize_names => true ) else raise ArgumentError "Cannot parse files of type #{data_file.extname}" end # Set key and freeze @key = key.freeze @data.freeze end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
53 54 55 |
# File 'lib/kerbaldyn/data.rb', line 53 def data @data end |
#key ⇒ Object (readonly)
Returns the value of attribute key.
53 54 55 |
# File 'lib/kerbaldyn/data.rb', line 53 def key @key end |
Class Method Details
.fetch(key) ⇒ Object
Fetch a data singleton by the stored key.
If the key is unknown, then it attempts to fetch the data from disk.
21 22 23 24 25 |
# File 'lib/kerbaldyn/data.rb', line 21 def self.fetch(key) registry = self.registry data_obj = registry.include?(key) ? registry[key] : registry[key]=self.new(key, FILE_MAP[key]) return data_obj.data end |
.registry ⇒ Object
A method for directly getting the registry; this shoudl typically be treated as private.
28 29 30 |
# File 'lib/kerbaldyn/data.rb', line 28 def self.registry return @registry ||= {} end |