Class: Nyanko::Loader

Inherits:
Object
  • Object
show all
Defined in:
lib/nyanko/loader.rb

Constant Summary collapse

UnitNotFound =
Class.new(StandardError)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Loader

Returns a new instance of Loader.



17
18
19
# File 'lib/nyanko/loader.rb', line 17

def initialize(name)
  @name = name
end

Class Method Details

.cacheObject



12
13
14
# File 'lib/nyanko/loader.rb', line 12

def cache
  @cache ||= {}
end

.load(unit_name) ⇒ Object



8
9
10
# File 'lib/nyanko/loader.rb', line 8

def load(unit_name)
  new(unit_name).load
end

Instance Method Details

#add_autoload_pathObject



46
47
48
49
# File 'lib/nyanko/loader.rb', line 46

def add_autoload_path
  ActiveSupport::Dependencies.autoload_paths << autoload_path
  ActiveSupport::Dependencies.autoload_paths.uniq!
end

#autoload_pathObject



51
52
53
# File 'lib/nyanko/loader.rb', line 51

def autoload_path
  Rails.root.join("#{directory_path}/#@name").to_s
end

#cacheObject



65
66
67
# File 'lib/nyanko/loader.rb', line 65

def cache
  self.class.cache
end

#constantizeObject



59
60
61
62
63
# File 'lib/nyanko/loader.rb', line 59

def constantize
  @name.to_s.camelize.constantize
rescue NameError
  raise UnitNotFound, "The unit for #{@name.inspect} is not found"
end

#directory_pathObject



55
56
57
# File 'lib/nyanko/loader.rb', line 55

def directory_path
  Config.units_directory_path
end

#loadObject



21
22
23
24
25
26
27
# File 'lib/nyanko/loader.rb', line 21

def load
  if loaded?
    load_from_cache
  else
    load_from_file
  end
end

#load_from_cacheObject



33
34
35
# File 'lib/nyanko/loader.rb', line 33

def load_from_cache
  cache[@name]
end

#load_from_fileObject



37
38
39
40
41
42
43
44
# File 'lib/nyanko/loader.rb', line 37

def load_from_file
  add_autoload_path
  cache[@name] = constantize
rescue Exception => exception
  ExceptionHandler.handle(exception)
  cache[@name] = false
  nil
end

#loaded?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/nyanko/loader.rb', line 29

def loaded?
  cache[@name] != nil
end