Module: Hanami::Model::Types::ClassMethods

Defined in:
lib/hanami/model/types.rb

Overview

Class level interface

Since:

  • 0.7.0

Instance Method Summary collapse

Instance Method Details

#Collection(type) ⇒ Object

Define an array of given type

Examples:

require "hanami/model"

class Account < Hanami::Entity
  attributes do
    # ...
    attribute :users, Types::Collection(User)
  end
end

 = Account.new(users: [User.new(name: "Luca")])
user    = .users.first
user.class # => User
user.name  # => "Luca"

 = Account.new(users: [{ name: "MG" }])
user    = .users.first
user.class # => User
user.name  # => "MG"

Parameters:

  • type (Object)

    an object

Since:

  • 0.7.0



76
77
78
79
# File 'lib/hanami/model/types.rb', line 76

def Collection(type)
  type = Schema::CoercibleType.new(type) unless type.is_a?(Dry::Types::Definition)
  Types::Array.member(type)
end

#Entity(type) ⇒ Object

Define an entity of the given type

Examples:

require "hanami/model"

class Account < Hanami::Entity
  attributes do
    # ...
    attribute :owner, Types::Entity(User)
  end
end

 = Account.new(owner: User.new(name: "Luca"))
.owner.class # => User
.owner.name  # => "Luca"

 = Account.new(owner: { name: "MG" })
.owner.class # => User
.owner.name  # => "MG"

Parameters:

Since:

  • 1.1.0



46
47
48
49
# File 'lib/hanami/model/types.rb', line 46

def Entity(type)
  type = Schema::CoercibleType.new(type) unless type.is_a?(Dry::Types::Definition)
  type
end