Class: Jimmy::FileMap
- Inherits:
-
Object
- Object
- Jimmy::FileMap
- Defined in:
- lib/jimmy/file_map.rb
Overview
Maps a directory of files to schemas with URIs. Can be used as a URI resolver with SchemerFactory.
Given ~/schemas/user.rb as a schema file:
file_map = FileMap.new('~/schemas', 'http://example.com/schemas/', suffix: '.json')
file_map.resolve('user.json') # => SchemaWithURI
Calling SchemaWithURI#as_json on the above will include the full ID http://example.com/schemas/user.json#
in the $id key.
Including the suffix in the call to #resolve is optional.
If you initialize a FileMap with live: true, files will be loaded lazily and repeatedly, every time #resolve or #index is called. This is intended as convenience for development environments.
Constant Summary collapse
Instance Method Summary collapse
-
#index ⇒ Jimmy::Index
Get an index of all schemas in the file map’s directory.
-
#initialize(base_dir, base_uri = nil, live: false, loaders: DEFAULT_LOADERS, suffix: '') ⇒ FileMap
constructor
A new instance of FileMap.
-
#live? ⇒ true, false
Returns true if live-reloading is enabled.
-
#resolve(uri) ⇒ Jimmy::SchemaWithURI?
(also: #[])
Given a URI, either absolute or relative to the file map’s base URI, returns a SchemaWithURI if a matching schema is found.
Constructor Details
#initialize(base_dir, base_uri = nil, live: false, loaders: DEFAULT_LOADERS, suffix: '') ⇒ FileMap
Returns a new instance of FileMap.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/jimmy/file_map.rb', line 47 def initialize( base_dir, base_uri = nil, live: false, loaders: DEFAULT_LOADERS, suffix: '' ) @dir = Pathname(base_dir).realpath unless @dir.directory? && @dir.readable? raise Error::BadArgument, 'Expected a readable directory' end base_uri ||= uri_for_dir @uri = Json::URI.new(base_uri.to_s, container: true) @live = live @loaders = loaders @suffix = suffix index unless live end |
Instance Method Details
#index ⇒ Jimmy::Index
Get an index of all schemas in the file map’s directory.
87 88 89 90 91 92 93 94 |
# File 'lib/jimmy/file_map.rb', line 87 def index return @index if @index index = build_index @index = index unless live? index end |
#live? ⇒ true, false
Returns true if live-reloading is enabled.
98 99 100 |
# File 'lib/jimmy/file_map.rb', line 98 def live? @live end |
#resolve(uri) ⇒ Jimmy::SchemaWithURI? Also known as: []
Given a URI, either absolute or relative to the file map’s base URI, returns a SchemaWithURI if a matching schema is found.
73 74 75 76 77 78 79 80 81 |
# File 'lib/jimmy/file_map.rb', line 73 def resolve(uri) uri = make_child_uri(uri) absolute_uri = @uri + uri return index.resolve(absolute_uri) unless live? schema = load_file(path_for_uri uri)&.get_fragment(uri.fragment) schema && SchemaWithURI.new(absolute_uri, schema) end |