Sha256: 523b1041db87ffa62335d3449c3768cbf78165095b84962945998aad119e8f98

Contents?: true

Size: 1.19 KB

Versions: 4

Compression:

Stored size: 1.19 KB

Contents

require "pathname"

module Nyanko
  class Loader
    UnitNotFound = Class.new(StandardError)

    class << self
      def load(unit_name)
        new(unit_name).load
      end

      def cache
        @cache ||= {}
      end
    end

    def initialize(name)
      @name = name
    end

    def load
      if loaded?
        load_from_cache
      else
        load_from_file
      end
    end

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

    def load_from_cache
      cache[@name]
    end

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

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

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

    def directory_path
      Config.units_directory_path
    end

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

    def cache
      self.class.cache
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
nyanko-0.0.9 lib/nyanko/loader.rb
nyanko-0.0.8 lib/nyanko/loader.rb
nyanko-0.0.7 lib/nyanko/loader.rb
nyanko-0.0.6 lib/nyanko/loader.rb