Class: Typesafe::Question

Inherits:
Object
  • Object
show all
Defined in:
lib/typesafe/question.rb

Overview

Abstract base class for the three question types understood by the TypeSafe System One API: Noul, Choice, and Score.

A question is an immutable value object. The question ID used to identify its answer is not part of the object: it is the Hash key under which the question is sent in a request, e.g.

questions = { refund_requested: Typesafe::Noul.new("Does the customer request a refund?") }

Direct Known Subclasses

Choice, Noul, Score

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(instructions) ⇒ Question

Returns a new instance of Question.

Parameters:

  • instructions (String)

    the question asked about the state.

Raises:

  • (ArgumentError)

    if instructions is not a non-empty String.



18
19
20
21
22
23
24
25
26
# File 'lib/typesafe/question.rb', line 18

def initialize(instructions)
  unless instructions.is_a?(String) && !instructions.strip.empty?
    raise ArgumentError, "instructions must be a non-empty String"
  end

  @instructions = instructions.dup.freeze
  validate!
  freeze
end

Instance Attribute Details

#instructionsString (readonly)

Returns the question asked about the state.

Returns:

  • (String)

    the question asked about the state.



14
15
16
# File 'lib/typesafe/question.rb', line 14

def instructions
  @instructions
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

Questions compare equal when they are of the same class and serialize to the same API shape.



46
47
48
# File 'lib/typesafe/question.rb', line 46

def ==(other)
  other.class == self.class && other.to_h == to_h
end

#hashObject



51
52
53
# File 'lib/typesafe/question.rb', line 51

def hash
  [self.class, to_h].hash
end

#to_hHash

Returns the question shape expected by the TypeSafe API.

Returns:

  • (Hash)

    the question shape expected by the TypeSafe API.



35
36
37
# File 'lib/typesafe/question.rb', line 35

def to_h
  { type: type, instructions: instructions }
end

#to_json(state = nil) ⇒ String

Returns the question serialized as JSON for the TypeSafe API.

Returns:

  • (String)

    the question serialized as JSON for the TypeSafe API.



40
41
42
# File 'lib/typesafe/question.rb', line 40

def to_json(state = nil)
  JSON.generate(to_h, state)
end

#typeString

Returns the API question type tag ("noul", "choice", or "score").

Returns:

  • (String)

    the API question type tag ("noul", "choice", or "score").

Raises:

  • (NotImplementedError)

    on the abstract base class.



30
31
32
# File 'lib/typesafe/question.rb', line 30

def type
  raise NotImplementedError, "#{self.class} must implement #type"
end