Class: Coercell::Parser

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

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ Parser

Returns a new instance of Parser.



7
8
9
# File 'lib/coercell.rb', line 7

def initialize(model)
  @model = model
end

Instance Method Details

#errorsObject



43
44
45
# File 'lib/coercell.rb', line 43

def errors
  @errors
end

#parse!Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/coercell.rb', line 21

def parse!
  data = []
  errors = []

  prepare_content
  
  @content.each_with_index do |line_data, i|
    instance = @model.new(line_data)
    if instance.valid?
      data << instance
    else
      error = {}
      error[:line] = i+2
      error[:messages] = instance.errors.full_messages
      errors << error
    end
  end

  @valid_objects = data 
  @errors = errors
end

#prepare_content(start = 2) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/coercell.rb', line 11

def prepare_content(start=2)
  @content ||= (start..spreadsheet.last_row).collect do |line|
    content_line = {}
    titles.each do |title|
      content_line[title[:value]] = get_cell_value(title,line)
    end
    content_line
  end
end

#spreadsheetObject



51
52
53
# File 'lib/coercell.rb', line 51

def spreadsheet
  @spreadsheet
end

#spreadsheet=(file) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/coercell.rb', line 55

def spreadsheet=(file)
  extension = File.extname(file)[1..-1].downcase

  @spreadsheet = case extension
          when "ods"
            Roo::Openoffice.new(file)
          when "xls"
            Roo::Excel.new(file)
          when "xlsx"
            Roo::Excelx.new(file)
          else
            raise ArgumentError, "Provided file must be Openffice(.ods) or Excel(.xls or .xlsx). .#{extension} is not valid"
          end
end

#valid_objectsObject



47
48
49
# File 'lib/coercell.rb', line 47

def valid_objects
  @valid_objects
end