class Todo::File

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

Public Class Methods

new(path, mode = 'r') click to toggle source

@param [String, Pathname] path @param [String] mode

# File lib/todo/file.rb, line 54
def initialize(path, mode = 'r')
  @ios = ::File.open(path, mode)
end
open(path, mode = 'r') { |ios| ... } click to toggle source

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

@param [String, Pathname] path @param [String] mode

# 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) click to toggle source

@param [String, Pathname] path

# 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) click to toggle source

@param [String, Pathname] path @param [Array, Todo::List] list

# 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

Public Instance Methods

close() click to toggle source

Closes the IO handle and flushes any pending writes.

# File lib/todo/file.rb, line 79
def close
  @ios.close
end
each() { |task| ... } click to toggle source

Executes the block for every task in the list.

# 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
Also aliased as: each_task
each_task()
Alias for: each
puts(*tasks) click to toggle source

Writes the given tasks to the underlying IO handle.

@overload puts(task, …)

@param [Todo::Task] task
@param [Todo::Task] ...
# File lib/todo/file.rb, line 74
def puts(*tasks)
  @ios.puts(tasks.map(&:to_s))
end