Skip to content

Instantly share code, notes, and snippets.

@glejeune
Created November 7, 2009 19:53
Show Gist options
  • Save glejeune/228854 to your computer and use it in GitHub Desktop.
Save glejeune/228854 to your computer and use it in GitHub Desktop.
ActiveRecord without Rails
require 'rubygems'
require 'ar'
class DBSchema < AR::Schema 1.0
def self.up
create_table :users do |t|
t.string :login
t.string :password
end
end
def self.down
drop_table :users
end
end
class User < AR::Model
end
AR.db_connect( "test.yml", "test.log" )
User.new( :login => "Muriel", :password => "leiruM" ).save
User.new( :login => "Greg", :password => "gerG" ).save
User.all.each do |u|
puts u.login
end
# => Muriel
# => Greg
begin
require 'active_record'
rescue LoadError => e
raise LoadError, "ActiveRecord ne doit pas être installé : #{e.message}"
end
class Object
def meta_def(m,&b)
(class<<self;self end).send(:define_method,m,&b)
end
end
class Hash
def keys_to_sym
self.each do |k, v|
self.delete(k)
self[k.to_s.to_sym] = v
end
end
end
module AR
Model = ActiveRecord::Base
class SchemaInfo < Model
end
def self.Schema( n )
@final = [n, @final.to_f].max
m = (@migrations ||= [])
Class.new(ActiveRecord::Migration) do
meta_def(:version) { n }
meta_def(:inherited) { |k| m << k }
end
end
class << self
def db_connect( dbfile, logfile )
dbconfig = YAML::load(File.open(dbfile)).keys_to_sym
version = dbconfig.delete(:schema_version) { |_| @final }
ActiveRecord::Base.establish_connection(dbconfig)
ActiveRecord::Base.logger = Logger.new(logfile)
if @migrations
unless SchemaInfo.table_exists?
ActiveRecord::Schema.define do
create_table SchemaInfo.table_name do |t|
t.column :version, :float
end
end
end
si = SchemaInfo.find(:first) || SchemaInfo.new(:version => 0)
@migrations.each do |k|
k.migrate(:up) if si.version < k.version and k.version <= version
k.migrate(:down) if si.version >= k.version and k.version > version
end
si.update_attributes(:version => version)
end
end
end
end
adapter: sqlite3
database: test.db
schema_version: 1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment