ActiveRecord
をstaticなデータに対しても使えると嬉しいけど、
ActiveModel
とかよくわからないので、
インメモリに展開したsqlite3を ActiveRecord
で扱えばいいじゃんっていう話。
一応、ActiveHash
とかのgemはあるらしけど完全互換じゃなかったので。
※注意
たぶんプロセスのメモリに展開するので、sinatra
とか rails
でやると残念なことになると思う
# !/usr/bin/env ruby
# coding:utf-8
require "active_record"
class InmemoryAR < ActiveRecord::Base
self.abstract_class = true
self.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
class Migration < ActiveRecord::Migration
def connection
@connection = InmemoryAR.connection
end
end
end
class TestMigration < InmemoryAR::Migration
def change
create_table :users do |t|
t.string :name
end
create_table :items do |t|
t.string :name
end
end
end
ActiveRecord::Migration.run(TestMigration)
data = YAML.load(DATA.read)
data.each { |table_name, records|
model = Class.new(InmemoryAR) {
self.table_name = table_name
}
self.class.const_set(model.table_name.classify, model)
records.each { |record|
model.create(record)
}
}
require "pp"
pp User.all
pp Item.all
__END__
---
users:
- name: foo
- name: bar
- name: baz
items:
- name: aaa
- name: bbb
- name: ccc