Class: EpubForge::Utils::FileOrderer

Inherits:
Object
  • Object
show all
Defined in:
lib/epubforge/utils/file_orderer.rb

Overview

FileOrderer holds a set of strings/regexes, then reorders a set of files (FunWith::Files::FilePaths, actually) by matching the filenames against one regex after another. Allows you to say, “I want the title page, the foreward, then all the chapters, then all the appendixes, then the afterword.” Ex: FileOrderer( [“title_page”, “forward”, “chapter-.*”, “afterword”, “appendix.*” ).reorder( pages ) Only compares the basename minus extension. Files should come from the same directory. cover.extension always comes first.

Instance Method Summary collapse

Constructor Details

#initialize(matchers) ⇒ FileOrderer

Returns a new instance of FileOrderer.



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/epubforge/utils/file_orderer.rb', line 10

def initialize( matchers )
  @matchers = matchers.map do |m| 
    case m
    when Regexp
      m
    when String
      /^#{m}$/
    end
  end
  
  @matchers.unshift( /^cover$/ )
  @matchers.push( /^.*$/ )
end

Instance Method Details

#reorder(files) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/epubforge/utils/file_orderer.rb', line 24

def reorder( files )
  files = files.map(&:fwf_filepath)
  
  ordered_files = @matchers.inject( [] ) do |collector, matcher|
    matched_files = files.select do |f| 
      name = f.basename_no_ext.to_s
      matcher.match( name )
    end
    
    matched_files.sort_by! do |filename|
      filename.basename_no_ext.to_s
    end
    
    collector += matched_files.sort
    files -= matched_files
    
    collector
  end
end