Class: Todo::File

Inherits:
Object
  • Object
show all
Defined in:
lib/todo/file.rb

Overview

A high level wrapper around the Ruby File interface which supports reading from and writing to an IO handle with Todo::Task objects.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, mode = 'r') ⇒ File

Returns a new instance of File.

Parameters:

  • path (String, Pathname)
  • mode (String) (defaults to: 'r')


54
55
56
# File 'lib/todo/file.rb', line 54

def initialize(path, mode = 'r')
  @ios = ::File.open(path, mode)
end

Class Method Details

.open(path, mode = 'r') ⇒ Object

Open a list file handle and pass it to the given block. The file is automatically closed when the block returns.

The file is opened in read-only mode by default.

Todo::File.open("~/Dropbox/todo/todo.txt") do |file|
  file.each_task do |task|
    puts task.done?
  end
end

Parameters:

  • path (String, Pathname)
  • mode (String) (defaults to: 'r')


18
19
20
21
22
23
24
25
26
27
# File 'lib/todo/file.rb', line 18

def self.open(path, mode = 'r')
  ios = new(path, mode)

  if block_given?
    yield ios
    return ios.close
  end

  ios
end

.read(path) ⇒ Object

Parameters:

  • path (String, Pathname)


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/todo/file.rb', line 30

def self.read(path)
  list = []

  open(path) do |file|
    file.each_task do |task|
      list << task
    end
  end

  list
end

.write(path, list) ⇒ Object

Parameters:

  • path (String, Pathname)
  • list (Array, Todo::List)


44
45
46
47
48
49
50
# File 'lib/todo/file.rb', line 44

def self.write(path, list)
  open(path, 'w') do |file|
    list.each do |task|
      file.puts(task)
    end
  end
end

Instance Method Details

#closeObject

Closes the IO handle and flushes any pending writes.



79
80
81
# File 'lib/todo/file.rb', line 79

def close
  @ios.close
end

#eachObject Also known as: each_task

Executes the block for every task in the list.



59
60
61
62
63
64
65
# File 'lib/todo/file.rb', line 59

def each
  return enum_for(:each) unless block_given?

  @ios.each_line do |line|
    yield Task.new(line)
  end
end

#puts(task, ...) ⇒ Object

Writes the given tasks to the underlying IO handle.

Parameters:



74
75
76
# File 'lib/todo/file.rb', line 74

def puts(*tasks)
  @ios.puts(tasks.map(&:to_s))
end