class CodeInventory::CSVFile

Attributes

csv[R]

Public Class Methods

new(csv_file) click to toggle source
# File lib/codeinventory/csv_file.rb, line 7
def initialize(csv_file)
  @csv = CSV.read(csv_file, { headers: true, converters: [ :integer ] })
  validate_headers
end

Public Instance Methods

projects() { |project| ... } click to toggle source
# File lib/codeinventory/csv_file.rb, line 12
def projects
  @csv.collect do |row|
    csv_data = row.to_hash
    project = csv_data.inject({}) do |memo, pair|
      csv_header, csv_value = pair
      case
      when csv_header == "tags"
        new_pair = { "tags" => csv_value.split(",").collect { |tag| tag.strip } }
      when csv_header.include?(".")
        new_pair = dotted_to_nested(csv_header, csv_value)
      else
        new_pair = { csv_header => csv_value }
      end
      memo.merge(new_pair)
    end
    yield project if block_given?
    project
  end
end

Private Instance Methods

dotted_to_nested(path, value) click to toggle source

Convert a dotted notation header and a value to a nested hash e.g., “contact.email” header with value “me@example.com” becomes { “contact” => { “email” => “me@example.com” } }

# File lib/codeinventory/csv_file.rb, line 37
def dotted_to_nested(path, value)
  path.split(".").reverse.inject(value) do |hash, element|
    { element => hash }
  end
end
validate_headers() click to toggle source
# File lib/codeinventory/csv_file.rb, line 43
def validate_headers
  required_headers = [ "name", "description", "license", "openSourceProject", "governmentWideReuseProject", "tags", "contact.email" ]
  required_headers.each do |required|
    raise FileFormatError unless @csv.headers.include? required
  end
end