Skip to content

Instantly share code, notes, and snippets.

@aaronblohowiak
Created October 24, 2008 21:37
Show Gist options
  • Save aaronblohowiak/19603 to your computer and use it in GitHub Desktop.
Save aaronblohowiak/19603 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'sinatra'
require 'activerecord'
require 'sqlite3'
configure do
ActiveRecord::Base.establish_connection(
:adapter=>'sqlite3', :dbfile=>'delish.db')
@results = ActiveRecord::Base.connection.execute(<<-TABLESQL)
SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
TABLESQL
(TABLES = @results.map{|r| r['name']}).each do | name |
Object.const_set(name.classify, Class.new(ActiveRecord::Base))
end
ActiveRecord::Base.class_eval do
def self.all_attributes
@@cached_attribs ||= ( primary_key.to_a + self.new.attribute_names ).uniq
end
def self.to_html
return "<div class=\"header\">" +
all_attributes.map do | attr |
"<div class=\"ar_attribute\"><div>#{attr}</div></div>"
end.join() + '</div>'
end
def to_html
return "<div>" +
self.class.all_attributes.map do | attr |
"<div class=\"ar_attribute\"><div>#{attributes[attr]}</div></div>"
end.join() + '</div>'
end
end
end
helpers do
def resourceful_request_for(splat)
klass, id = splat.split('/')
id, format = id.split('.') if id
klass, format = klass.split('.') unless format
[format, klass, id]
end
end
get "/" do
@title = "Browsing your database via html, json and xml."
erb :list
end
get "/*" do
format, klass, id = resourceful_request_for(params[:splat].first)
@klass = Object.const_get(klass.classify)
@objects = Array(@klass.find( id || :all))
format ? @objects.send("to_#{format}") : erb(:show)
end
use_in_file_templates!
__END__
@@ layout
<head>
<title><%= @title || @objects.first.class.table_name %></table>
</head>
<body style="width:100%;margin:0;padding:0;">
<%= yield %>
</body>
@@ list
<%= [nil, '.json', '.xml'].map do | extension |
TABLES.map {| table | "<a href=\"/#{table}#{ext}\">#{table}#{ext}</a> " }
end.join('<br/>') %>
@@ show
<style type="text/css">
<% col_width = 100 / @objects.first.class.all_attributes.length %>
.ar_attribute{
width : <%= col_width %>%;
height: 100px;
float: left;
border:1px solid #ccc;
}
.ar_attribute div{
padding:1em 0.5em;
overflow:auto;
}
.header .ar_attribute{
background-color:black;
color:white;
height:3em;
}
</style>
<%= @objects.first.class.to_html %>
<%= @objects.map{|o| o.to_html }.join %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment