Sha256: 40c776dc96c5738c871dae4186237c3d86826c0db887eaec7cf035c5cd451244

Contents?: true

Size: 1.59 KB

Versions: 2

Compression:

Stored size: 1.59 KB

Contents

module ObjectLoader
  module ClassMethods
    #
    # Loads a block for the Class.
    #
    # @param [String] path
    #   The path to load the block from.
    #
    # @return [Proc]
    #   The block defined for the Class.
    #
    # @since 1.0.0
    #
    def load_object_block(path)
      ObjectLoader.load_blocks(path)[self]
    end

    #
    # Loads a compatible object.
    #
    # @param [String] path
    #   The path to load the object from.
    #
    # @param [Array] arguments
    #   Additional arguments to use when creating the object.
    #
    # @return [Object]
    #   The loaded object.
    #
    # @since 1.0.0
    #
    def load_object(path,*arguments)
      pending = ObjectLoader.load_blocks(path)

      pending_class, pending_block = pending.find do |klass,block|
        klass.ancestors.include?(self)
      end

      if (pending_class && pending_block)
        obj = pending_class.new(*arguments)
        obj.instance_eval(&pending_block)
        obj
      end
    end

    #
    # Creates a loadable object using the arguments and block.
    #
    # @param [Array] args
    #   Additional arguments to pass to the Classes `new` method.
    #
    # @yield []
    #   The given block will be instance evaled into the newly created
    #   object when the object is loaded.
    #
    # @since 1.0.0
    #
    def object(*args,&block)
      if (args.empty? && ObjectLoader.is_pending?)
        ObjectLoader.pending[self] = block
        return nil
      else
        new_object = self.new(*args)
        new_object.instance_eval(&block) if block
        return new_object
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
object_loader-1.0.1 lib/object_loader/class_methods.rb
object_loader-1.0.0 lib/object_loader/class_methods.rb