Sha256: 7c95ff43be3b0721fe0e111e2327bb19f92d9f49346a36dfb0f5086365f724f5

Contents?: true

Size: 1.05 KB

Versions: 2

Compression:

Stored size: 1.05 KB

Contents

require 'dry/types'

module ROM
  module Plugins
    module Relation
      module Schema
        def self.included(klass)
          super

          klass.class_eval do
            def self.schema(&block)
              @__schema__ = Schema.create(&block) if block_given?
              @__schema__
            end
          end
        end

        class Schema
          attr_reader :schema
          attr_reader :coercer

          def self.create(&block)
            new.tap { |schema| schema.instance_eval(&block) }
          end

          def initialize(schema = {}, coercer = Dry::Types['hash'])
            @schema = schema
            @coercer = coercer
          end

          def attribute_names
            schema.keys
          end

          def apply(attributes = {})
            coercer.schema(schema).call(attributes)
          end

          private

          def attribute(name, type)
            schema[name] = type
          end
        end
      end
    end
  end
end


ROM.plugins do
  register :schema, ROM::Plugins::Relation::Schema, type: :relation
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rom-http-0.4.0 lib/rom/plugins/relation/schema.rb
rom-http-0.3.0 lib/rom/plugins/relation/schema.rb