3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

staticなデータを ActiveRecord で扱う

Last updated at Posted at 2016-04-05

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
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?