read

This is a nasty and naughty hack, and one I’m abashedly apologetic for.

I was doing some work on a personal project recently, and wanted to pull some data out of the live database. I only needed a few columns from a couple of tables, so it didn’t seem to warrant a SQL dump.

I decided to format the records as JSON data, and copy/paste them from the console directly. But it turned out the length of the JSON data was longer than the backtrace in my terminal window, so I wasn’t able to see it all at once to select, copy, and paste.

Instead, I decided to save the data in a temporary file, and then email it to myself—using a temporary, memory-only mailer object.

Since this code was only held in memory during my rails console session, it disappeared as soon as I exited the session.

Here’s the code I used to do that:

array = # ... get all of the data that I need from the DB

# Create the Tempfile object
tempfile = Tempfile.new("my-data")
# Write the data to the tempfile as JSON
tempfile.write(array.to_json)

# Subclass ApplicationMailer in memory
class DynamicMailer < ApplicationMailer

  # Define a mailer method to send myself the file we just created
  def send_attachment(tempfile)
    attachments['attached.json'] = File.read(tempfile.path)
    mail(to: 'me@handyrailstips.com',
         body: "",
         subject: "Incoming...")
  end

end
# Send the email
DynamicMailer.send_attachment(tempfile).deliver_now

# Clean up the Tempfile afterwards
tempfile.close
tempfile.unlink

Hopefully the annotations in the code example make sense.

  1. I pulled the data that I wanted from the database in an Array of Hashes
  2. I created a Tempfile to store the data in
  3. I wrote the data to the Tempfile in the JSON format
  4. I created a new Mailer class in memory with one method for sending attached files
  5. I sent myself the Tempfile full of JSON
  6. I cleaned up the Tempfile afterwards.

I don’t advise that you ever use this horrible little hack for anything, on any project, ever.