Class: Typesafe::Answer

Inherits:
Object
  • Object
show all
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

ChoiceAnswer, NoulAnswer, ScoreAnswer

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_h(hash) ⇒ NoulAnswer, ...

Builds the typed answer matching +hash+'s type tag.

Parameters:

  • hash (Hash)

    one entry of the API response's answers map, with String or Symbol keys.

Returns:

Raises:

  • (ArgumentError)

    if hash is not a Hash or its type is missing or unknown.



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

#hashObject



63
64
65
# File 'lib/typesafe/answer.rb', line 63

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

#to_hHash

Returns the answer shape returned by the TypeSafe API.

Returns:

  • (Hash)

    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.

Returns:

  • (String)

    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

#typeString

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

Returns:

  • (String)

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

Raises:

  • (NotImplementedError)

    on the abstract base class.



42
43
44
# File 'lib/typesafe/answer.rb', line 42

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