Module: HeartSeed::Converter

Defined in:
lib/heart_seed/converter.rb

Constant Summary collapse

HEADER_ROW =
1

Class Method Summary collapse

Class Method Details

.convert_to_yml(source_file: nil, source_sheet: nil, dist_file: nil) ⇒ Hash{ String => Hash{ String => Object } }

convert xls,xlsx to yaml and write to file.

example

source xls

id, title, description, created_at
1, title1, description1, 2014-06-01 12:10:00 +0900
2, title2, description2, 2014-06-02 12:10:00 +0900

output yaml

---
articles_1:
  id: 1
  title: title1
  description: description1
  created_at: '2014-06-01 12:10:00 +0900'
articles_2:
  id: 2
  title: title2
  description: description2
  created_at: '2014-06-02 12:10:00 +0900'

Parameters:

  • source_file (String) (defaults to: nil)

    source file (xls, xlsx)

  • source_sheet (String) (defaults to: nil)
  • dist_file (String) (defaults to: nil)

    don't write to file if blank

Returns:

  • (Hash{ String => Hash{ String => Object } })


35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/heart_seed/converter.rb', line 35

def self.convert_to_yml(source_file: nil, source_sheet: nil, dist_file: nil)
  sheet = open_file(source_file).sheet(source_sheet)
  return nil if empty_sheet?(sheet)

  fixtures = read_sheet(sheet, source_sheet)

  unless dist_file.blank?
    File.open(dist_file, "w") do |f|
      f.write(YAML.dump(fixtures))
    end
  end

  fixtures
end

.read_fixture_yml(source_file) ⇒ Array<Hash>

Returns rows.

Parameters:

  • source_file (String)

    source yml file

Returns:

  • (Array<Hash>)

    rows



53
54
55
# File 'lib/heart_seed/converter.rb', line 53

def self.read_fixture_yml(source_file)
  YAML.load_file(source_file).values
end

.select_left_of_blank(array) ⇒ Object



121
122
123
124
125
126
127
128
129
# File 'lib/heart_seed/converter.rb', line 121

def self.select_left_of_blank(array)
  response = []
  array.each do |element|
    break unless element
    break if element.respond_to?(:blank?) && element.blank?
    response << element
  end
  response
end

.table_sheets(source_file) ⇒ Array<String>

Returns sheet names (rejected multi-byte sheet).

Parameters:

  • source_file

Returns:

  • (Array<String>)

    sheet names (rejected multi-byte sheet)



60
61
62
63
# File 'lib/heart_seed/converter.rb', line 60

def self.table_sheets(source_file)
  # reject multi-byte sheet
  open_file(source_file).sheets.select{|sheet| sheet =~ /^[A-Za-z0-9_]+$/ }
end