Custom schema is optional for SQL databases, while it’s mandatory for entities without a database table, or while using with a non-SQL database.
Custom schema takes precedence over automatic schema. If we use custom schema, we need to manually add all the new columns from the corresponding SQL database table.
Let’s instantiate it with proper values:
user.name # => "Luca"
user.age # => 35
user.email # => "luca@hanami.test"
user.codes # => nil
user.comments # => nil
user = User.new(codes: ["123", "456"])
user.codes # => [123, 456]
Other entities can be passed as concrete instance:
user = User.new(comments: [Comment.new(text: "cool")])
user.comments
Or as data:
It enforces data integrity via exceptions:
User.new(comments: [:foo]) # => TypeError: :foo must be coercible into Comment
Strict mode
# lib/bookshelf/entities/user.rb
class User < Hanami::Entity
EMAIL_FORMAT = /\@/
attributes :strict do
attribute :id, Types::Strict::Int
attribute :name, Types::Strict::String
attribute :email, Types::Strict::String.constrained(format: EMAIL_FORMAT)
attribute :age, Types::Strict::Int.constrained(gt: 18)
end
user = User.new(id: 1, name: "Luca", age: 35, email: "luca@hanami.test")
user.id # => 1
user.name # => "Luca"
user.age # => 35
user.email # => "luca@hanami.test"
It cannot be instantiated with missing keys
User.new(id: 1, name: "Luca", age: 35)
# => ArgumentError: :email is missing in Hash input
Or with nil
:
User.new(id: 1, name: nil, age: 35, email: "luca@hanami.test")
# => TypeError: nil (NilClass) has invalid type for :name violates constraints (type?(String, nil) failed)
It accepts strict values and it doesn’t attempt to coerce:
# => TypeError: "1" (String) has invalid type for :id violates constraints (type?(Integer, "1") failed)
Learn more about data types in the dedicated article.