Method: ROM::Relation::ClassInterface#schema

Defined in:
lib/rom/relation/class_interface.rb

#schema(dataset = nil, as: nil, infer: false, &block) ⇒ Schema

Specify canonical schema for a relation

With a schema defined commands will set up a type-safe input handler automatically

Examples:

class Users < ROM::Relation[:sql]
  schema do
    attribute :id, Types::Serial
    attribute :name, Types::String
  end
end

# access schema from a finalized relation
users.schema

Parameters:

  • dataset (Symbol) (defaults to: nil)

    An optional dataset name

  • infer (Boolean) (defaults to: false)

    Whether to do an automatic schema inferring

Returns:



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/rom/relation/class_interface.rb', line 92

def schema(dataset = nil, as: nil, infer: false, &block)
  if defined?(@schema) && !block && !infer
    @schema
  elsif block || infer
    raise MissingSchemaClassError.new(self) unless schema_class

    ds_name = dataset || schema_opts.fetch(:dataset, default_name.dataset)
    relation = as || schema_opts.fetch(:relation, ds_name)

    raise InvalidRelationName.new(relation) if invalid_relation_name?(relation)

    @relation_name = Name[relation, ds_name]

    @schema_proc = proc do |*args, &inner_block|
      schema_dsl.new(
        relation_name,
        schema_class: schema_class,
        attr_class: schema_attr_class,
        inferrer: schema_inferrer.with(enabled: infer),
        &block
      ).call(*args, &inner_block)
    end
  end
end