Class: IOHelpers::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/io_helpers/reader.rb

Class Method Summary collapse

Class Method Details

.file(path, options = {}) ⇒ Object



3
4
5
6
7
# File 'lib/io_helpers/reader.rb', line 3

def self.file(path, options = {})
  line_sep = options[:line_sep] || "\n"
  lines = File.readlines(path, line_sep, chomp: true)
  map_lines(lines, options)
end

.map_element(element, as, mapper) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/io_helpers/reader.rb', line 30

def self.map_element(element, as, mapper)
  if mapper
    mapper.call(element)
  else
    element.method("to_#{as}").call
  end
end

.map_lines(lines, options) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/io_helpers/reader.rb', line 19

def self.map_lines(lines, options)
  col_sep = options[:col_sep]
  as = options[:as] || 's'
  mapper = options[:mapper]
  if col_sep
    lines.map { |line| line.split(col_sep).map { |col| map_element(col, as, mapper) } }
  else
    lines.map { |line| map_element(line, as, mapper) }
  end
end

.stream(path) ⇒ Object



15
16
17
# File 'lib/io_helpers/reader.rb', line 15

def self.stream(path)
  IO.foreach(path).lazy
end

.string(str, options = {}) ⇒ Object



9
10
11
12
13
# File 'lib/io_helpers/reader.rb', line 9

def self.string(str, options = {})
  line_sep = options[:line_sep] || "\n"
  lines = str.split(line_sep)
  map_lines(lines, options)
end