Skip to content

Instantly share code, notes, and snippets.

@kwando
Last active April 19, 2016 08:07
Show Gist options
  • Save kwando/1feaba05b1a5513ffb444eb6e28ab21e to your computer and use it in GitHub Desktop.
Save kwando/1feaba05b1a5513ffb444eb6e28ab21e to your computer and use it in GitHub Desktop.
Schema support for your adapter
require 'dry/types'
module ROM
module Plugins
module Relation
module Schema
Undefined = Object.new.freeze
def self.included(klass)
super
klass.extend(ClassMethods)
klass.include(InstanceMethods)
end
module InstanceMethods
def schema
self.class.schema
end
def each
return to_enum unless block_given?
super { |e| yield(schema.call(e)) }
self
end
def attributes
schema.member_types.keys
end
def base_name
dataset.table.name
end
end
module ClassMethods
def schema(value = Undefined)
if value != Undefined
@__schema = Dry::Types['hash'].symbolized(value)
elsif !schema?
@__schema = NullSchema.new(self.to_s)
end
@__schema
end
def schema?
!@__schema.nil?
end
end
class NullSchema
def initialize(relation_name)
@relation_name = relation_name
end
def call(value)
value
end
def member_types
raise("no schema defined for #{@relation_name}")
end
end
end
end
end
end
ROM.plugins do
register :schema, ROM::Plugins::Relation::Schema, type: :relation
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment