Skip to content

Instantly share code, notes, and snippets.

@kwando
Created February 13, 2017 14:34
Show Gist options
  • Save kwando/fac39e7a2c61bfb44873e4f1207ff663 to your computer and use it in GitHub Desktop.
Save kwando/fac39e7a2c61bfb44873e4f1207ff663 to your computer and use it in GitHub Desktop.
Custom read type ruby repo
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
@kwando
Copy link
Author

kwando commented Feb 13, 2017

That last line return a string but I'm expecting a Hash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment