Add direct yaml and json support to resources.
authorSimon Cross <hodgestar@gmail.com>
Sat, 17 May 2014 14:47:10 +0000 (16:47 +0200)
committerSimon Cross <hodgestar@gmail.com>
Sat, 17 May 2014 14:47:41 +0000 (16:47 +0200)
naja/resources/__init__.py
naja/resources/loader.py

index 191cbd4170fe20399dcb6acd8bd764b0c9933c94..b080786609851f3953531ef5f47e682e7ef6256e 100644 (file)
@@ -1,3 +1,5 @@
-from naja.resources.loader import Loader
+from naja.resources.loader import Loader, ResourceNotFound
+
+__all__ = ['resources', 'ResourceNotFound']
 
 resources = Loader('data')
 
 resources = Loader('data')
index 28a3c7a3fdf0f39cb85918d3f97f0dbb964b69e0..69eff2fed3fafa891fb9e8c32dbbfd090d24f360 100644 (file)
@@ -1,5 +1,6 @@
 import os
 import sys
 import os
 import sys
+import json
 
 try:
     from pkg_resources import resource_filename
 
 try:
     from pkg_resources import resource_filename
@@ -11,6 +12,12 @@ except ImportError:
         # time going down this rabbithole already
         return os.path.join(os.path.dirname(__file__), '..', '..', 'data',
                             path)
         # time going down this rabbithole already
         return os.path.join(os.path.dirname(__file__), '..', '..', 'data',
                             path)
+
+try:
+    import yaml
+except ImportError:
+    yaml = None
+
 import pygame
 
 
 import pygame
 
 
@@ -99,3 +106,15 @@ class Loader(object):
             self._cache[key] = pygame.font.Font(fn, font_size)
 
         return self._cache[key]
             self._cache[key] = pygame.font.Font(fn, font_size)
 
         return self._cache[key]
+
+    def get_yaml(self, *path_fragments):
+        if yaml is None:
+            raise ResourceNotFound("%s - %s" % (
+                os.path.join(*path_fragments),
+                "YAML module not available"))
+        with self.get_file(*path_fragments) as yaml_file:
+            return yaml.safe_load(yaml_file)
+
+    def get_json(self, *path_fragments):
+        with self.get_file(*path_fragments) as json_file:
+            return json.load(json_file)