Sha256: 8f6bb95b1f19c8f1d1dec9189e4ace9565a5d8ec94f683e6b37aa22f5425fc64

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module DirModel
  module Import
    extend ActiveSupport::Concern

    attr_reader :context, :source_path, :index, :previous

    def initialize(path, options={})
      @source_path, @context = path, OpenStruct.new(options[:context])
      @index, @previous = options[:index], options[:previous].try(:dup)
      @load_state = :ghost
      @file_infos = {}
    end

    def matches
      load
      file_infos[:options][:match]
    end

    def image
      File.open(source_path)
    end

    def skip?
      load
      !@_match
    end

    def method_missing(name, *args, &block)
      load
      matches[name]
    rescue IndexError
      super
    end

    module ClassMethods
      def next(path, context={}, previous=nil)
        path.read_path
        new(path.current_path, index: path.index, context: context, previous: previous)
      end
    end

    private

    attr_reader :load_state, :file_infos

    def match?
      return if load_state == :loaded

      @_match ||= begin
        loader do
          self.class.file_names.each do |file_name|
            options = self.class.options(file_name)

            if match = (source_path||'').match(options[:regex].call)
              @file_infos = { file: file_name, options: options.merge(match: match) }
              return true
            end
          end
          false
        end
      end
    end
    alias_method :load, :match?

    def loader
      @load_state = :loading
      result = yield
      @load_state = :loaded
      result
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dir_model-0.3.0 lib/dir_model/import.rb