So I was messing around with some scratchpad code today, investigating the use of with_exclusive_scope, and here’s what I had to write to come up with a minimal working ActiveRecord model:
require 'rubygems' require 'active_record' ActiveRecord::Base.establish_connection( :adapter => "sqlite3", :database => ":memory:") ActiveRecord::Base.connection.create_table(:monsters) do |t| t.string :name end class Monster < ActiveRecord::Base end cm = Monster.create(:name => "Cookie Monster")
For little one-off demo scripts that seems a bit excessive to me. For comparison, here’s the equivalent DataMapper:
require 'rubygems' require 'datamapper' class Monster include DataMapper::Resource property :name, String, :key => true end DataMapper.setup(:default, 'sqlite::memory:') DataMapper.auto_migrate! cm = Monster.create(:name => "Cookie Monster")
Can anyone golf the ActiveRecord down any smaller?
EDIT: Thanks to Jacob Rothstein for this version:
require 'active_record' class Monster < ActiveRecord::Base establish_connection :adapter => 'sqlite3', :database => ':memory:' connection.create_table( :monsters ) { |t| t.string :name } cm = create :name => 'cookie monster' end
I think you're picking at nits for a) how excessive the AR version is and b) how gloriously terse the DM version is. Yes, the DM version is a little shorter. But the key reasons it is shorter has little to do with what sets DM apart as nicer — e.g. mixin vs inheritance (AR is shorter), properties in class with automigration (AR is about the same with one column, and shorter with more) — and everything to do with the setup/establish_connection methods (DM's terse connection string is arguably more cryptic than a config hash) and that “ActiveRecord::Base” is almost twice as long as “DataMapper”, both of which are nice and all… but not all that important to normal measures of excessive, even in minimal scratchpad scripts.
That said, if it's golf you want, then here's a very half-hearted golf attempt:
ARB = ActiveRecord::Base
ARB.establish_connection :adapter => “sqlite3”, :database => “:memory:”
ARB.connection.create_table(:monsters) {|t| t.string :name }
class Monster < ARB; end
and, to be an equal opportunity obfuscator, here's the same level of effort for DM:
DM = DataMapper
class Monster; include DM::Resource; property :name, String, :key => true; end
DM.setup(:default, 'sqlite::memory:'); DM.auto_migrate!
(no more than 78 col per line in both examples)
I think you're reading too much into this. I just wanted to know if there was a shorter version of the AR code that I could use for demo scripts. As it turns out, there is – see the edit above, courtesy Jacob Rothstein.
There ought to be a way to replace that connection hash with a connection URL like “sqlite3://:memory:”, but I can’t figure out the precise format.