Created
February 13, 2017 14:34
-
-
Save kwando/fac39e7a2c61bfb44873e4f1207ff663 to your computer and use it in GitHub Desktop.
Custom read type ruby repo
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 'bundler' | |
Bundler.setup | |
require 'sequel' | |
DB = Sequel.connect('sqlite::memory') | |
DB.create_table(:users) do | |
primary_key(:id) | |
String :name, null: false | |
String :data, null: false | |
end | |
require 'rom' | |
require 'rom-repository' | |
require 'json' | |
require 'rom-sql' | |
EncodeJSON = ROM::SQL::Types::String.constructor { |x| JSON.generate(x) } | |
DecodeJSON = ROM::SQL::Types::Hash.constructor do |value| | |
case value | |
when String then | |
JSON.parse(value) | |
elsea | |
value | |
end | |
end | |
rom = ROM.container(:sql, DB) { |config| | |
config.relation(:users) { | |
schema(:users, infer: true) { | |
attribute :data, EncodeJSON.meta(read: DecodeJSON) | |
config.commands(:users) { | |
define(:create) { | |
result(:one) | |
} | |
} | |
} | |
} | |
} | |
class UserRepo < ROM::Repository[:users] | |
def find(id) | |
users.where(id: id).one! | |
end | |
end | |
users = UserRepo.new(rom) | |
puts user = rom.command(:users).create[name: 'Hello World', data: {username: 'kwando'}] | |
puts rom.relation(:users).where(id: user.fetch(:id)) | |
puts users.find(user.fetch(:id)).data.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That last line return a string but I'm expecting a Hash.