Class: Masamune::Schema::Map::Buffer

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/masamune/schema/map.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(map, table) ⇒ Buffer

Returns a new instance of Buffer.



92
93
94
95
96
97
# File 'lib/masamune/schema/map.rb', line 92

def initialize(map, table)
  @map      = map
  @table    = table
  @store    = table.store
  @line     = 0
end

Instance Attribute Details

#lineObject (readonly)

Returns the value of attribute line.



145
146
147
# File 'lib/masamune/schema/map.rb', line 145

def line
  @line
end

Instance Method Details

#append(data) ⇒ Object



114
115
116
117
118
119
120
121
122
123
# File 'lib/masamune/schema/map.rb', line 114

def append(data)
  raise 'must call Buffer#bind first' unless @io
  row = safe_row(data)
  return unless row
  write_headers = @store.headers && @line < 1
  @csv ||= CSV.new(@io, options.merge(headers: row.headers, write_headers: write_headers))
  @csv << row.serialize if row.valid? && append?(row.serialize)
ensure
  @line += 1
end

#bind(io) ⇒ Object



99
100
101
102
# File 'lib/masamune/schema/map.rb', line 99

def bind(io)
  @io = io.set_encoding('binary', 'UTF-8', undef: :replace)
  @csv = nil
end

#eachObject



104
105
106
107
108
109
110
111
112
# File 'lib/masamune/schema/map.rb', line 104

def each
  raise 'must call Buffer#bind first' unless @io
  CSV.parse(JSONEncoder.new(@io, @store), options.merge(headers: @store.headers || @table.columns.keys)) do |data|
    next if data.to_s.start_with?('#')
    row = safe_row(data)
    yield row.to_hash if row
    @line += 1
  end
end

#to_sObject



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/masamune/schema/map.rb', line 125

def to_s
  case @io
  when File, Tempfile
    @io.path
  when IO
    case @io.fileno
    when 0
      'STDIN'
    when 1
      'STDOUT'
    when 2
      'STDERR'
    else
      'UNKNOWN'
    end
  when StringIO
    'StringIO'
  end
end