Class: WordTree::Disk::Library

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/wordtree/disk/library.rb

Constant Summary collapse

FILE_TYPES =
{
  :raw => "%s.md"
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Library

Returns a new instance of Library.



19
20
21
# File 'lib/wordtree/disk/library.rb', line 19

def initialize(root)
  @root = root
end

Instance Attribute Details

#rootObject (readonly)

The file path to the root of the library directory, e.g. /data/library



17
18
19
# File 'lib/wordtree/disk/library.rb', line 17

def root
  @root
end

Instance Method Details

#dir_of(book_id) ⇒ Object

returns the full path of a book’s subdirectory within the library Accepts either a String or a LibraryLocator object



25
26
27
# File 'lib/wordtree/disk/library.rb', line 25

def dir_of(book_id)
  File.expand_path(LibraryLocator.identity(book_id).relpath, root)
end

#each(file_suffix_re = /\.(md|txt)$/, &block) ⇒ Object

Breadth-first search of the directory structure, operating on each book



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/wordtree/disk/library.rb', line 45

def each(file_suffix_re=/\.(md|txt)$/, &block)
  Find.find(@root) do |path|
    if FileTest.directory?(path)
      if File.basename(path)[0] == ?.
        # Don't look any further into this directory.
        Find.prune
      else
        next
      end
    elsif path =~ file_suffix_re
      yield path
    end
  end
end

#file_type(book_id, type = :raw) ⇒ Object



33
34
35
36
# File 'lib/wordtree/disk/library.rb', line 33

def file_type(book_id, type=:raw)
  locator = LibraryLocator.identity(book_id)
  FILE_TYPES[type] % locator.id
end

#mkdir(book_id) ⇒ Object

Create all subdirs up to the location where a book is stored Accepts either a String or a LibraryLocator object



40
41
42
# File 'lib/wordtree/disk/library.rb', line 40

def mkdir(book_id)
  FileUtils.mkdir_p(dir_of(book_id))
end

#path_to(book_id, type = :raw) ⇒ Object



29
30
31
# File 'lib/wordtree/disk/library.rb', line 29

def path_to(book_id, type=:raw)
  File.join(dir_of(book_id), file_type(book_id, type))
end