Class: Typesafe::Question
- Inherits:
-
Object
- Object
- Typesafe::Question
- 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?") }
Instance Attribute Summary collapse
-
#instructions ⇒ String
readonly
The question asked about the state.
Instance Method Summary collapse
-
#==(other) ⇒ Object
(also: #eql?)
Questions compare equal when they are of the same class and serialize to the same API shape.
- #hash ⇒ Object
-
#initialize(instructions) ⇒ Question
constructor
A new instance of Question.
-
#to_h ⇒ Hash
The question shape expected by the TypeSafe API.
-
#to_json(state = nil) ⇒ String
The question serialized as JSON for the TypeSafe API.
-
#type ⇒ String
The API question type tag ("noul", "choice", or "score").
Constructor Details
#initialize(instructions) ⇒ Question
Returns a new instance of Question.
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
#instructions ⇒ String (readonly)
Returns 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 |
#hash ⇒ Object
51 52 53 |
# File 'lib/typesafe/question.rb', line 51 def hash [self.class, to_h].hash end |
#to_h ⇒ Hash
Returns 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.
40 41 42 |
# File 'lib/typesafe/question.rb', line 40 def to_json(state = nil) JSON.generate(to_h, state) end |
#type ⇒ String
Returns the API question type tag ("noul", "choice", or "score").
30 31 32 |
# File 'lib/typesafe/question.rb', line 30 def type raise NotImplementedError, "#{self.class} must implement #type" end |