Sha256: 9c3e53eac26d43908361e9d15cadea1fffa0bc82a543ee7cb5e8d197608bcc21

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

class ActiveModel::Csvrizer::Railtie < Rails::Railtie
  initializer 'csverizer' do
    ActiveSupport.on_load(:action_controller) do
      ActionController::Renderers.add :csv do |object, options|
        filename = options.fetch(:filename, 'data')
        begin
          serializer =
            if object.respond_to?(:each)
              hash = options.slice(:each_serializer)
              ActiveModel::CsvArraySerializer.new(object, hash)
            else
              hash = options.slice(:serializer)
              ActiveModel::CsvrizerFactory.new(object, hash)
            end
          data = serializer.to_csv
        # TODO: probably should implement a specialized exception for this
        #   this btw is when a serializer is not found for provided object
        rescue NameError
          data = object.respond_to?(:to_csv) ? object.to_csv : object.to_s
        end
        send_data(
          data,
          type: Mime[:csv],
          disposition: "attachment; filename=#{filename}.csv"
        )
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
csverizer-0.0.4 lib/active_model/csverizer/railtie.rb