Class: Typesafe::Answer
- Inherits:
-
Object
- Object
- Typesafe::Answer
- Defined in:
- lib/typesafe/answer.rb
Overview
Abstract base class for the three answer types returned by the TypeSafe System One API: NoulAnswer, ChoiceAnswer, and ScoreAnswer.
An answer is an immutable value object mirroring its question: it carries what the model returned for one question, but not the question id — that is the Hash key under which the answer appears in a Response.
Use Answer.from_h (or Response.from_json) to build typed answers from a parsed response body:
Typesafe::Answer.from_h({ "type" => "noul", "noul" => 0.95 })
# => #<Typesafe::NoulAnswer @noul=0.95>
Direct Known Subclasses
Class Method Summary collapse
-
.from_h(hash) ⇒ NoulAnswer, ...
Builds the typed answer matching +hash+'s
typetag.
Instance Method Summary collapse
-
#==(other) ⇒ Object
(also: #eql?)
Answers compare equal when they are of the same class and serialize to the same API shape.
- #hash ⇒ Object
-
#to_h ⇒ Hash
The answer shape returned by the TypeSafe API.
-
#to_json(state = nil) ⇒ String
The answer serialized as JSON.
-
#type ⇒ String
The API answer type tag ("noul", "choice", or "score").
Class Method Details
.from_h(hash) ⇒ NoulAnswer, ...
Builds the typed answer matching +hash+'s type tag.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/typesafe/answer.rb', line 24 def self.from_h(hash) unless hash.is_a?(Hash) raise ArgumentError, "answer must be a Hash, got #{hash.inspect}" end type = hash["type"] || hash[:type] case type when "noul" then NoulAnswer.from_h(hash) when "choice" then ChoiceAnswer.from_h(hash) when "score" then ScoreAnswer.from_h(hash) else raise ArgumentError, "unknown answer type #{type.inspect} (expected \"noul\", \"choice\", or \"score\")" end end |
Instance Method Details
#==(other) ⇒ Object Also known as: eql?
Answers compare equal when they are of the same class and serialize to the same API shape.
58 59 60 |
# File 'lib/typesafe/answer.rb', line 58 def ==(other) other.class == self.class && other.to_h == to_h end |
#hash ⇒ Object
63 64 65 |
# File 'lib/typesafe/answer.rb', line 63 def hash [self.class, to_h].hash end |
#to_h ⇒ Hash
Returns the answer shape returned by the TypeSafe API.
47 48 49 |
# File 'lib/typesafe/answer.rb', line 47 def to_h { type: type } end |
#to_json(state = nil) ⇒ String
Returns the answer serialized as JSON.
52 53 54 |
# File 'lib/typesafe/answer.rb', line 52 def to_json(state = nil) JSON.generate(to_h, state) end |
#type ⇒ String
Returns the API answer type tag ("noul", "choice", or "score").
42 43 44 |
# File 'lib/typesafe/answer.rb', line 42 def type raise NotImplementedError, "#{self.class} must implement #type" end |