Skip to content

Instantly share code, notes, and snippets.

@larsthegeek
Forked from jacaetevha/database_cards.rb
Last active August 29, 2015 14:17
Show Gist options
  • Save larsthegeek/b347a11cfa5ddb4e9265 to your computer and use it in GitHub Desktop.
Save larsthegeek/b347a11cfa5ddb4e9265 to your computer and use it in GitHub Desktop.
# Run this file by placing it in your Rails application's script directory.
# Then you invoke it with:
#
# rails runner script/cards.rb
#
# Or if you are running Zeus:
#
# zeus runner script/cards.rb
require "rubygems"
require "prawn"
require "bundler/setup"
class Card
attr_reader :table_name, :columns, :body
TYPES = {
"integer" => "INT",
"float" => "FLT",
"datetime" => "D/T",
"boolean" => "BOOL",
"string" => "STR",
"text" => "TXT"
}
def initialize(table_name, columns)
@table_name = table_name
@columns = columns_as_string columns
@body = @columns.join("\n")
end
private
def columns_as_string(columns)
columns.map do |column|
type = (TYPES[column.type.to_s] || "??#{column.type}").ljust(5, " ")
"<font name='Courier'><strong><sup><color rgb='AB66FF'>#{type}</color></sup></strong></font>#{column.name} "
end
end
end
class Prawn::Document
CARD_WIDTH = 72 * 7 # 7 inches
CARD_HEIGHT = 72 * 5 # 5 inches
SPACE_BETWEEN_COLUMN_NAMES = 2
def self.generate_cards(outfile, cards)
generate(outfile, :page_layout => :portrait) do
row = 2
font "Helvetica"
cards.each do |card|
if row == 0
start_new_page
row = 2
end
draw_card(card, row)
row -= 1
end
end
end
def margin_box(margin, &block)
bounding_box [bounds.left + margin, bounds.top - margin],
width: bounds.width - (margin * 2), height: bounds.height - (margin * 2),
&block
end
def outline_box
stroke_rectangle bounds.top_left, bounds.width, bounds.height
end
def draw_card(card, row)
y_offset = CARD_HEIGHT * row + ((bounds.height - (2*CARD_HEIGHT))/2)
bounding_box [0, y_offset], width: CARD_WIDTH, height: CARD_HEIGHT-10 do # offset the height by a little bit in order to separate the bounding boxes
outline_box
margin_box 8 do
text card.table_name.upcase, :size => 18
move_down 2
# stroke_horizontal_rule
margin_box 12 do
font "Times-Roman"
move_down 20
column_box([0, cursor], columns: 2, width: bounds.width, height: CARD_HEIGHT - 50) do
text card.body, size: 13, align: :left, leading: SPACE_BETWEEN_COLUMN_NAMES, inline_format: true
end
end
end
end
end
end
def generate_pdf(cards)
file = ARGV[0] || 'tmp/cards.pdf'
Prawn::Document.generate_cards(file, cards)
puts "check #{file}"
end
connection = ActiveRecord::Base.connection
cards = []
(connection.tables - ['schema_migrations']).sort.each do |table_name|
cards << Card.new(table_name, connection.columns(table_name))
end
generate_pdf cards
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment