Sha256: 0bdc5574afb01e1f2f178107e5b244cee2330e4296a6718643d28d32db4b9022

Contents?: true

Size: 1.95 KB

Versions: 1

Compression:

Stored size: 1.95 KB

Contents

class Report < ActiveRecord::Base
  include AASM

  # CSV Attachment
  validates_inclusion_of :type, :in => MintReporter.config.reports
  has_attached_file(:csv, MintReporter.config.paperclip_storage_options)
  do_not_validate_attachment_file_type :csv
  after_commit :generate_csv, :on => :create

  ### AASM States ###
  aasm :column => 'state' do
    initial_state :pending

    state :pending
    state :generating_csv
    state :csv_generated
    state :csv_ready
    state :csv_failed

    event :generating_csv do
      transitions :from => [
        :pending,
        :generating_csv,
        :csv_failed
      ], :to => :generating_csv
    end
    event :csv_generated do
      transitions :from => [:generating_csv, :csv_generated, :csv_failed],
       :to => :csv_generated
    end
    event :csv_ready  do
      transitions :from => [:csv_generated, :csv_ready], :to => :csv_ready
    end
    event :csv_failure do
      transitions :from => [:generating_csv, :csv_ready, :csv_failed],
       :to => :csv_failed
    end
  end

  def generate_csv
    CSVGenerationWorker.perform_async(id)
  end

  def generate_csv!
    generating_csv!
    file = Tempfile.new(["report-#{id}", '.csv'])
    begin
      CSV.open(file, "wb") do |csv|
        csv << csv_column_names

        scoped_records.each do |record|
          csv << csv_row(record)
        end
      end
      self.csv = file
      save
      file.close
      csv_generated!
    rescue Exception => e
      csv_failure!
      raise e
    end
  end

  def csv_column_names
    raise MintReporter::Undefined,
      "Subclasses of Report must implement csv_column_names"
  end

  def csv_row(record)
    raise MintReporter::Undefined,
      "Subclasses of Report must implement csv_row"
  end

  def records
    raise MintReporter::Undefined,
      "Subclasses of Report must implement records"
  end

  private

  def scoped_records
    records.where(:created_at => from_date..to_date).
      order(:created_at => :desc)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mint_reporter-0.0.7 app/models/report.rb