Module: Horza::DependencyLoading
- Extended by:
- DependencyLoading
- Included in:
- DependencyLoading
- Defined in:
- lib/horza/dependency_loading.rb
Constant Summary collapse
- Error =
Class.new(StandardError)
- MissingFile =
Class.new(Error)
Instance Method Summary collapse
- #constant_name_for_path(file_path) ⇒ Object
- #resolve_dependency(entity_name) ⇒ Object
- #resolve_from_file_paths(entity_name) ⇒ Object
-
#search_for_file(path_suffix) ⇒ Object
Search for a file matching the provided suffix.
Instance Method Details
#constant_name_for_path(file_path) ⇒ Object
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/horza/dependency_loading.rb', line 37 def constant_name_for_path(file_path) ActiveSupport::Dependencies.loadable_constants_for_path( file_path, Horza.constant_paths ).tap do |loadables| if loadables.many? raise "It seems that your registered constant file paths are not setup correctly " + "and would cause Horza to try and load the following constants:\n\n #{loadables.map(&:inspect).join(', ')}" end end end |
#resolve_dependency(entity_name) ⇒ Object
8 9 10 11 12 13 |
# File 'lib/horza/dependency_loading.rb', line 8 def resolve_dependency(entity_name) file_name = entity_name.to_s.underscore # Search for a matching filename in #constant_paths # and try to load a constant that matches. resolve_from_file_paths(file_name) end |
#resolve_from_file_paths(entity_name) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/horza/dependency_loading.rb', line 15 def resolve_from_file_paths(entity_name) if Horza.constant_paths.empty? # try in current scope, even with no lookup paths configured begin entity_name.capitalize.constantize rescue NameError raise ArgumentError.new("No file paths configured to lookup constants") end else file_path = search_for_file(entity_name) resolved_name = constant_name_for_path(file_path).first if resolved_name.nil? Error.new("No constant found for: #{entity_name.inspect}") else ActiveSupport::Dependencies::Reference.safe_get(resolved_name) end end end |
#search_for_file(path_suffix) ⇒ Object
Search for a file matching the provided suffix. This recursively checks directories in the #Horza.constant_paths for matches.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/horza/dependency_loading.rb', line 50 def search_for_file(path_suffix) path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb") Horza.constant_paths.each do |root| Dir.glob(File.join(root, "**/")).each do |dir| path = File.join(dir, path_suffix) return path if File.file? path end end raise MissingFile.new( "No matching file found for: '#{path_suffix.sub(/(\.rb)?$/, "")}'\n" + "Searched in: (#{Horza.constant_paths.map(&:inspect).join(', ')})" ) end |