Sha256: 63d8ee929a2a6b3f1827fa166b506de9bdcd9ed313a79acb4037ee9dba632ecd

Contents?: true

Size: 876 Bytes

Versions: 3

Compression:

Stored size: 876 Bytes

Contents

require "pluck_map/errors"

module PluckMap
  module CsvPresenter

    def to_csv(query)
      if attributes.nested?
        raise PluckMap::UnsupportedAttributeError, "to_csv can not be used to present nested attributes"
      end

      define_to_csv!
      to_csv(query)
    end

    private def define_to_csv!
      require "csv"

      headers = CSV.generate_line(attributes.map(&:name))
      ruby = <<-RUBY
      def to_csv(query)
        pluck(query) do |results|
          rows = [#{headers.inspect}]
          results.each_with_object(rows) do |values, rows|
            values = Array(values)
            rows << CSV.generate_line([#{attributes.map(&:to_ruby).join(", ")}])
          end.join
        end
      end
      RUBY
      # puts "\e[34m#{ruby}\e[0m" # <-- helps debugging PluckMapPresenter
      class_eval ruby, __FILE__, __LINE__ - 7
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pluck_map-1.0.0 lib/pluck_map/presenters/to_csv.rb
pluck_map-1.0.0.rc2 lib/pluck_map/presenters/to_csv.rb
pluck_map-1.0.0.rc1 lib/pluck_map/presenters/to_csv.rb