Class: SimpleCsv::Reader

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

Constant Summary

Constants inherited from Base

Base::COMMON_DELIMITERS

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, **opts, &block) ⇒ Reader

Returns a new instance of Reader.



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/simple_csv/reader.rb', line 5

def initialize(path, **opts, &block)
  @csv_path = File.expand_path path
  @caller_self = eval 'self', block.binding

  opts[:seperator] ||= detect_delimiter
  settings.apply opts

  load_csv_with_auto_headers if settings.for_csv[:headers]

  instance_exec(self, &block)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mtd, *args, &block) ⇒ Object (private)



59
60
61
62
63
64
# File 'lib/simple_csv/reader.rb', line 59

def method_missing(mtd, *args, &block)
  m = mtd.to_s
  return @record[m] if headers.include?(m)
  return @record[@col_map[m]] if @col_map.key?(m)
  @caller_self.send mtd, *args, &block
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



3
4
5
# File 'lib/simple_csv/reader.rb', line 3

def index
  @index
end

Instance Method Details

#each_row(*arr_opts, &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/simple_csv/reader.rb', line 26

def each_row(*arr_opts, &block)
  @index ||= 0 if arr_opts.include?(:with_index)

  load_csv_with_manual_headers unless @csv

  @csv.each do |record|
    @record = record
    instance_exec(self, &block)
    @index += 1 if @index
  end
end

#in_groups_of(size, &block) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/simple_csv/reader.rb', line 17

def in_groups_of(size, &block)
  @original.each_slice(size) do |group|
    @csv = group
    instance_exec(self, &block)
  end
  @index = nil
  @csv = @original
end