Module: Valkyrie::Types

Includes:
ArrayDefault
Defined in:
lib/valkyrie/types.rb

Overview

Note:

Not all Dry::Types built-in types are supported in Valkyrie

Namespace for Dry::Types types.

Includes Dry::Types built-in types and defines custom Valkyrie types

Types allow your models to automatically cast attributes to the appropriate type or even fail to instantiate should you give an inappropriate type.

Examples:

Use types in property definitions on a resource

class Book < Valkyrie::Resource
  attribute :title, Valkyrie::Types::Set.optional  # default type if none is specified
  attribute :member_ids, Valkyrie::Types::Array
end

See Also:

Defined Under Namespace

Modules: ArrayDefault, Params

Constant Summary collapse

ID =

Valkyrie::ID

Dry::Types::Nominal
     .new(Valkyrie::ID)
     .constructor do |input|
  if input.respond_to?(:each)
    # Solr::ORMConverter tries to pass an array of Valkyrie::IDs
    Valkyrie::ID.new(input.first)
  else
    Valkyrie::ID.new(input)
  end
end
URI =

Valkyrie::URI

Dry::Types::Nominal
      .new(RDF::URI)
      .constructor do |input|
  if input.present?
    RDF::URI.new(input.to_s)
  else
    input
  end
end
OptimisticLockToken =

Optimistic Lock Token

Dry::Types::Nominal
.new(::Valkyrie::Persistence::OptimisticLockToken)
.constructor do |input|
  Valkyrie::Persistence::OptimisticLockToken.deserialize(input)
end
Anything =

Used for casting Resources if possible.

Valkyrie::Types::Any.constructor do |value|
  if value.respond_to?(:fetch) && value.fetch(:internal_resource, nil)
    resource_klass = Valkyrie.config.resource_class_resolver.call(value.fetch(:internal_resource))
    resource_klass.new(value)
  else
    value
  end
end
Array =
Dry::Types['array'].constructor do |value|
  if value.is_a?(::Hash)
    if value.empty?
      []
    else
      [value]
    end
  else
    ::Array.wrap(value)
  end
end.default([].freeze)
Set =

Represents an array of unique values.

Array.constructor do |value|
  value = Array[value]
  clean_values = value.reject do |val|
    (val.is_a?(Valkyrie::ID) && val.to_s == '') || val == ''
  end.reject(&:nil?).uniq

  clean_values.map do |val|
    Anything[val]
  end
end.default([].freeze)
Relation =
Valkyrie::Types::Set.of(Valkyrie::Types::ID)
OrderedRelation =
Valkyrie::Types::Array.of(Valkyrie::Types::ID).meta(ordered: true)
SingleValuedString =

Used for when an input may be an array, but the output needs to be a single string.

Valkyrie::Types::String.constructor do |value|
  ::Array.wrap(value).first.to_s
end

Method Summary

Methods included from ArrayDefault

#of