Class: Omakase::Type

Inherits:
Object
  • Object
show all
Defined in:
lib/omakase/type.rb

Overview

A return type that is a Ruby class: the model builds the object in code and hands the object itself back, so nothing goes through JSON.

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Type

Returns a new instance of Type.



7
8
9
# File 'lib/omakase/type.rb', line 7

def initialize(klass)
  @klass = klass
end

Instance Method Details

#code_only?Boolean

Only code can build it, so :predict is not a fallback.

Returns:

  • (Boolean)


20
# File 'lib/omakase/type.rb', line 20

def code_only? = true

#definitionObject Also known as: json

Raises:



28
29
30
# File 'lib/omakase/type.rb', line 28

def definition
  raise Error, "returns: #{@klass} needs the :code_act strategy — the model has to build the object in code"
end

#describeObject

A Struct or Data says what it holds, and the model needs that to build one: Refund.new(order_id:, amount:, reason:) beats a Refund.



13
14
15
16
17
# File 'lib/omakase/type.rb', line 13

def describe
  return "a #{@klass}" unless @klass.respond_to?(:members)

  "#{@klass}.new(#{@klass.members.map { |name| "#{name}:" }.join(", ")})"
end

#take(value) ⇒ Object

Raises:



22
23
24
25
26
# File 'lib/omakase/type.rb', line 22

def take(value)
  return value if value.is_a?(@klass)

  raise ContractError, "expected #{describe}, got #{value.class}"
end