Sha256: 80427f11d885324fd1b080ee906549105a1468dc370655c91ea9bb377ea94b7c

Contents?: true

Size: 887 Bytes

Versions: 1

Compression:

Stored size: 887 Bytes

Contents

module DataModel
	module Model
		extend self

		def defaults
			{
				# name of validator if a child, and validating a named property
				property: nil,

				# context passed to read and write
				config: {},
				types: nil,
				children: [],

				# default writer
				write: ->(val) { val }
			}
		end

		def validate!(model)
			model => {
				property:, config:, types:,
				read: Proc, write: Proc,
				children: Array,
			}
		end

		def read(model, data)
			validate! model
			invoke(model, :read, data)
		end

		def write(model, data)
			validate! model
			invoke(model, :write, data)
		end

		private

		def invoke(model, action, data)
			fn = model.fetch(action)

			case fn.arity
			when 1
				fn.call(data)
			when 2
				ctx = model.slice(:config, :types, :children)
				fn.call(data, ctx)
			else
				raise "expected an arity of 1 or 2, got: #{fn.arity}"
			end
		end
	end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
data_model-0.0.1 lib/data_model/model.rb