Module: IMW::Resources::LocalFile

Defined in:
lib/imw/resources/local.rb

Overview

Defines methods for appropriate for a local file.

Instance Method Summary collapse

Instance Method Details

#dump(data, options = {}) ⇒ Object

Dump data into this file.

Parameters:

  • data (String, Array, #each)

    object to dump

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :persist (true, false) — default: false

    Don’t close the file after writing



120
121
122
123
124
125
# File 'lib/imw/resources/local.rb', line 120

def dump data, options={}
  data.each do |element|  # works if data is an Array or a String
    io.puts(element.to_s)
  end
  io.close unless options[:persist]
end

#ioFile

Return the IO object at this path.

Returns:

  • (File)


73
74
75
# File 'lib/imw/resources/local.rb', line 73

def io
  @io ||= open(path, mode)
end

#load {|String| ... } ⇒ Array

Return the lines in this file.

If passed a block, yield each line of the file to the block.

Yields:

  • (String)

    each line of the file

Returns:

  • (Array)

    the lines in the file



99
100
101
102
103
104
105
106
107
# File 'lib/imw/resources/local.rb', line 99

def load &block
  if block_given?
    io.each do |line|
      yield line
    end
  else
    read.split("\n")
  end
end

#map {|String| ... } ⇒ Object

Map over the lines in this file.

Yields:

  • (String)

    each line of the file



112
113
114
# File 'lib/imw/resources/local.rb', line 112

def map &block
  io.map(&block)
end

#read(length = nil) ⇒ String

Read from this file.

Parameters:

  • length (Fixnum) (defaults to: nil)

    bytes to read

Returns:



81
82
83
# File 'lib/imw/resources/local.rb', line 81

def read length=nil
  io.read(length)
end

#rmObject Also known as: rm!

Delete this resource.



63
64
65
66
67
# File 'lib/imw/resources/local.rb', line 63

def rm
  should_exist!("Cannot delete")
  FileUtils.rm path
  self
end

#write(text) ⇒ Fixnum

Write to this file

Parameters:

  • text (String, #to_s)

    text to write

Returns:

  • (Fixnum)

    bytes written



89
90
91
# File 'lib/imw/resources/local.rb', line 89

def write text
  io.write text
end