Created
January 29, 2015 21:06
-
-
Save solnic/82a379f1e0bcc4a8c53b to your computer and use it in GitHub Desktop.
ActiveROM ;)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rom-sql' | |
require 'virtus' | |
module ActiveRecord | |
class Base | |
def self.inherited(klass) | |
rel_class = Class.new(ROM::Relation[:sql]) { | |
base_name Inflecto.tableize(klass.name).to_sym | |
} | |
dataset = repository.dataset(rel_class.base_name) | |
attributes = dataset.columns | |
mod = Module.new { | |
include Virtus.module | |
attributes.each { |name| attribute(name) } | |
} | |
klass.send(:include, mod) | |
klass.class_eval do | |
class << self | |
attr_accessor :relation, :mapper | |
end | |
end | |
klass.mapper = Class.new(ROM::Mapper) { | |
model klass | |
attributes.each { |name| attribute(name) } | |
}.build | |
klass.relation = rel_class.new(dataset) | |
klass.send(:include, Equalizer.new(*attributes)) | |
super | |
end | |
def self.rom | |
ROM.env | |
end | |
def self.repository | |
rom.repositories[:default] | |
end | |
def self.find(id) | |
map(relation.where(id: id)).first | |
end | |
def self.first | |
map(relation.limit(1)).first | |
end | |
def self.create(tuple) | |
find(relation.insert(tuple)) | |
end | |
def self.map(relation) | |
mapper.process(relation) | |
end | |
end | |
end | |
setup = ROM.setup(:sql, 'postgres://localhost/rom') | |
setup.default.connection.drop_table?(:users) | |
setup.default.connection.create_table(:users) do | |
primary_key :id | |
String :name | |
String :email | |
end | |
ROM.finalize | |
class User < ActiveRecord::Base | |
end | |
puts User.create(name: 'Piotr', email: '[email protected]').inspect | |
# => #<User id=1 name="Piotr" email="[email protected]"> | |
puts User.first.inspect | |
# => #<User id=1 name="Piotr" email="[email protected]"> | |
# | |
puts User.find(1).inspect | |
# => #<User id=1 name="Piotr" email="[email protected]"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment