class ChupaText::Decomposers::CSV

Public Instance Methods

decompose(data) { |text_data| ... } click to toggle source
# File lib/chupa-text/decomposers/csv.rb, line 38
def decompose(data)
  text = ""
  data.open do |input|
    begin
      csv = ::CSV.new(input, liberal_parsing: true)
      csv.each do |row|
        text << row.join("\t")
        text << "\n"
      end
    rescue ::CSV::MalformedCSVError => csv_error
      error do
        message = "#{log_tag} Failed to parse CSV: "
        message << "#{csv_error.class}: #{csv_error.message}\n"
        message << csv_error.backtrace.join("\n")
        message
      end
      return
    end
  end

  text_data = TextData.new(text, :source_data => data)
  if data.need_screenshot?
    text_data.screenshot = create_screenshot(data, text)
  end

  yield(text_data)
end
target?(data) click to toggle source
# File lib/chupa-text/decomposers/csv.rb, line 27
def target?(data)
  return true if data.mime_type == "text/csv"

  if data.text_plain? and
      (data["source-mime-types"] || []).include?("text/csv")
    return false
  end

  data.extension == "csv"
end

Private Instance Methods

create_screenshot(data, text) click to toggle source
# File lib/chupa-text/decomposers/csv.rb, line 67
      def create_screenshot(data, text)
        width, height = data.expected_screenshot_size
        max_n_lines = 10
        font_size = height / max_n_lines
        target_text = ""
        text.each_line.with_index do |line, i|
          break if i == max_n_lines
          target_text << line
        end
        mime_type = "image/svg+xml"
        data = <<-SVG

<svg
  xmlns="http://www.w3.org/2000/svg"
  width="#{width}"
  height="#{height}"
  viewBox="0 0 #{width} #{height}">
  <text
    x="0"
    y="#{font_size}"
    style="font-size: #{font_size}px; white-space: pre-wrap;"
    xml:space="preserve">#{CGI.escapeHTML(target_text)}</text>
</svg>
        SVG
        Screenshot.new(mime_type, data)
      end
log_tag() click to toggle source
# File lib/chupa-text/decomposers/csv.rb, line 94
def log_tag
  "[decomposer][csv]"
end